"I'm trying to execute "main.py" file which is written in Python by my .net core web API but i got an exception.
I already give the permission of my Web API folder as well as my Python Code folder.
var file = Configuration.GetValue<string>("DE.PythonPath");
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = file;
start.Arguments = string.Format("{0} {1}", cmd, args);
start.UseShellExecute = false;
start.RedirectStandardOutput = true;
using (Process process = Process.Start(start))
{
string stderr = process.StandardError.ReadToEnd();
using (StreamReader reader = process.StandardOutput)
{
string result = reader.ReadToEnd();
return result;
}
}
I expect the python code run but it gives exception "The requested operation requires elevation"
Visual studio need to be run as admin. So run the Visual studio as Run as Administrator
Related
So im trying to run python code in C#. But when I'm trying to execute the command I get a error message:
System.ComponentModel.Win32Exception: 'Access Denied'
Code:
private void run_cmd(string cmd, int args)
{
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = "C://Users//user//AppData//Local//Microsoft//WindowsApps//python.exe";
start.Arguments = string.Format("{0} {1}", cmd, args);
start.UseShellExecute = false;
start.RedirectStandardOutput = true;
using (Process process = Process.Start(start))
{
using (StreamReader reader = process.StandardOutput)
{
string result = reader.ReadToEnd();
Console.Write(result);
}
}
}
The error is happening at:
using (Process process = Process.Start(start))
Process.Start Method is not supported in UWP apps. To run the exe file from your UWP app, I'd suggest you use FullTrustProcessLauncher Class.
First, you need to copy the exe file and save it in the UWP app package, for example, the Assets folder. Then please go to the Manifest file and add the runFullTrust restricted capability.(App capability). Next, add the reference of Windows Desktop Extensions for the UWP project. At last, you could call await FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync(); to launch the exe file from your app.
im trying to execute some python code from C#, so i have this code :
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = #"C:\Users\protieax\PycharmProjects\untitled\venv\Scripts\python.exe";
start.Arguments = "request.py 31.12.2016 01.01.2017 datatype"; // give filename, dates from the UI to python and query datatype
start.UseShellExecute = false;
start.RedirectStandardOutput = true;
using (Process process = Process.Start(start))
{
using (StreamReader reader = process.StandardOutput)
{
string result = reader.ReadToEnd();
Console.Write(result);
}
}
It should work but the C# doesnt find the python file.
What i should put in those 2 variables? Thanks
EDIT :
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = #"U:\Documents\entsoe-py-master\tests\test_data";
start.Arguments = "request.py 31.12.2016 01.01.2017 datatype"; // give filename, dates from the UI to python and query datatype
start.UseShellExecute = false;
start.RedirectStandardOutput = true;
using (Process process = Process.Start(start))
{
using (StreamReader reader = process.StandardOutput)
{
string result = reader.ReadToEnd();
Console.Write(result);
}
}
Here is my code modified with your answers. I have a new error :
System.ComponentModel.Win32Exception: 'The system cannot find the file specified'
At the line
using (Process process = Process.Stqrt(start))
You specified a U drive, presumably a network drive. I've never used a network drive in a context like this one but I tried it to find out if that's the problem. I mounted a network drive with U being the label. After running the code, it failed and gave me the same error. I advise making a copy of the desired python script into your current working directory instead, it would make things a lot more simple.
I followed this_link and I was able to run a dummy python file from my c# code like this...
public JsonResult FetchscrapyDataUrl(String website)
{
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = #"C:\ProgramData\Anaconda3\python.exe";
start.Arguments = #"C:\Users\PycharmProjects\scraping_web\scrape_info\main.py";
//this is path to .py file from scrapy project
start.CreateNoWindow = false; // We don't need new window
start.UseShellExecute = false; // Do not use OS shell
//start.RedirectStandardOutput = true;// Any output, generated by application will be redirected back
start.RedirectStandardError = true; // Any error in standard output will be redirected back (for example exceptions)
Console.WriteLine("Python Starting");
start.RedirectStandardOutput = true;
using (Process process = Process.Start(start))
{
using (StreamReader reader = process.StandardOutput)
{
string stderr = process.StandardError.ReadToEnd(); // Here are the exceptions from our Python script
string result = reader.ReadToEnd(); // Here is the result of StdOut(for example: print "test")
Console.Write(result);
}
}
}
Now I know that I can run scrapy spider from a single file main.py like this...
from scrapy import cmdline
cmdline.execute("scrapy crawl text".split())
When I run main.py file from cmd in windows it works fine but it does not work when I run it from C# code .Net framework. The error is ...
"Scrapy 1.4.0 - no active project\r\n\r\nUnknown command: crawl\r\n\r\nUse \"scrapy\" to see available commands\r\n"
Any Idea how to run this...Or am i missing some path setting in windows ??
Or should I run my spider from C# in some other way??
You need to set the WorkingDirectory property
start.WorkingDirectory = #"C:\Users\PycharmProjects\scraping_web\scrape_info\"
Or you need to cd to that directory to make it work
I am running a python script from a C# application. The script runs fine on command prompt/terminal but fails to execute when invoked via C# code.
It says Resource u'corpora/stopwords' not found. Please use the NLTK Downloader to obtain the resource: >>> nltk.download() even though I have all the required data/stopwords
Below is the error report from debug tab in Visual Studios.
Traceback (most recent call last):
File "C:\Users\Amey\Anaconda3\envs\dato-env\TrainingSetsUtil.py", line 20, in <module>
stopwords = set(stopwords.words('english'))
File "C:\Users\Amey\Anaconda3\envs\dato-env\lib\site-packages\nltk\corpus\util.py", line 99, in __getattr__
self.__load()
File "C:\Users\Amey\Anaconda3\envs\dato-env\lib\site-packages\nltk\corpus\util.py", line 64, in __load
except LookupError: raise e
LookupError:
**********************************************************************
Resource u'corpora/stopwords' not found. Please use the NLTK
Downloader to obtain the resource: >>> nltk.download()
Searched in:
- 'nltk_data'
**********************************************************************
Here's the invoking code.
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = #"C:\Users\Amey\Anaconda3\envs\dato-env\python.exe";
start.Arguments = #"C:\Users\Amey\Anaconda3\envs\dato-env\TrainingSetsUtil.py " + uname;
start.UseShellExecute = false;// Do not use OS shell
start.CreateNoWindow = true; // We don't need new window
start.RedirectStandardOutput = true;// Any output, generated by application will be redirected back
start.RedirectStandardError = true; // Any error in standard output will be redirected back (for example exceptions)
using (Process process = Process.Start(start))
{
using (StreamReader reader = process.StandardOutput)
{
string stderr = process.StandardError.ReadToEnd(); // Here are the exceptions from our Python script
string result = reader.ReadToEnd(); // Here is the result of StdOut(for example: print "test")
Console.WriteLine(result);
Console.WriteLine(stderr);
}
}
I eventually want to be able to return a DataFrame from Python to C#. At the moment I am running a very simple console app to try and run a basic Python script. This script compiles and runs in Canopy fine however when I run it from C# I get the error relating to non-ASCII chars.
I have read many articles relating to this but none of them seem to resolve the issue I have.
Error
SyntaxError: Non-ASCII character '\x90' in file C:\Program Files\Enthought\Canop
y32\App\appdata\canopy-1.5.2.2785.win-x86\python.exe on line 1, but no encoding
declared; see http://www.python.org/peps/pep-0263.html for details
Thx in advance for any help!
static int test_python_canopy()
{
string cmd;
string args;
args = "C:\\Share\\Python\\test.py";
cmd = #"C:\Program Files\Enthought\Canopy32\App\appdata\canopy-1.5.2.2785.win-x86\python.exe";
cmd = "\"" + cmd + "\"";
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = cmd;
start.Arguments = string.Format("{0} {1}", cmd, args);
start.UseShellExecute = false;
start.RedirectStandardOutput = true;
using (Process process = Process.Start(start))
{
using (StreamReader reader = process.StandardOutput)
{
string result = reader.ReadToEnd();
Console.Write(result);
}
}
return 0;
}
For ProcessStartInfo, FileName should be set to the executable that you wish to run and Arguments should be set to the arguments that you want to pass to that executable.
In your code, FileName is set correctly to the Python interpreter. Arguments, however, the first argument is being set to Python interpreter. The net result is that C# is trying to execute this command:
C:\Program Files\Enthought\Canopy32\App\appdata\canopy-1.5.2.2785.win-x86\python.exe C:\Program Files\Enthought\Canopy32\App\appdata\canopy-1.5.2.2785.win-x86\python.exe C:\Share\Python\test.py
which means that Python is trying to use the Python executable as a script, which is not going to work. Changing the line that sets the arguments should fix the problem:
start.Arguments = args;