I have anaconda3 installed on my Windows 10 machine.
I want to get the python script to run and return the results to C#.
So here is my code in C#:
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = #"C:\Users\John\AppData\Local\Cotinum\anaconda3\python.exe";
start.Arguments = string.Format("{0}", #"C:\test.py", "test");
start.UseShellExecute = false;
start.RedirectStandardOutput = true;
using(Process process = Process.Start(start))
using (StreamReader reader = process.StandardOutput)
{
string foo = reader.ReadToEnd();
TxtResultOutput.Text += foo;
}
The python code
import pandas as pd
import sys
def test_func(f_name):
a = pd.read_excel(f_name)
return a
if __name__ == "__main__":
f_name = sys.argv[1]
test_func(f_name)
When I run C# code, in the output window of Visual Studio. It shows the error:
File "C:\Users\John\AppData\Local\Continuum\anaconda3\lib\site-package\pandas__init__.py", line 19,
in module
"Missing required dependencies {0}".format(missing_dependencies))
ImportError: Missing required dependencies ['numpy']
However I don't believe I missed it because I can run the script from anaconda3 prompt window. It must be that somehow the PATH can't found in Visual Studio/ C# environment.
Related
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);
}
}
is it possible to use python tools for visual studio in visual studio such that it allows for side by side coding of ASP.NET C# application and some python code?
Secondly how do i call a python script from C#?
Thanks in advance.
As for running python scripts in C# you can always do something like this:
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = "path/to/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);
}
}
Passing python script as cmd and arguments as args.
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;
I want to run the following python script using C# and MonoDevelop and execute the code.
My Mono Develop code
string command = "python";
string argss = "/home/xyz/script.py A_file B_file";
string verb = "";
ProcessStartInfo procInfo = new ProcessStartInfo();
procInfo.WindowStyle = ProcessWindowStyle.Normal;
procInfo.UseShellExecute = false;
procInfo.FileName = command;
procInfo.Arguments = argss;
procInfo.Verb = verb;
Process.Start(procInfo);
The above code is not working. It is showing A_file & B_File are not accessible.
even A_File & B_File has been give full permission & file is placed at same location.
python script is working correctly when compile directly on terminal.
I am running MonoDevelop on Ubuntu