有没有办法使用 c# 执行 python 程序?
is there a way to execute a python program using c#?
我想使用 c# 调用我的 python 程序并让它在调用时自动执行。我已经完成了打开程序,但如何 运行 它并获得输出。这是我最后一年的项目,请帮助我 out.Here 是我的代码:
Process p = new Process();
ProcessStartInfo pi = new ProcessStartInfo();
pi.UseShellExecute = true;
pi.FileName = @"python.exe";
p.StartInfo = pi;
try
{
p.StandardOutput.ReadToEnd();
}
catch (Exception Ex)
{
}
以下代码执行 python 调用模块的脚本和 return 结果
class Program
{
static void Main(string[] args)
{
RunPython();
Console.ReadKey();
}
static void RunPython()
{
var args = "test.py"; //main python script
ProcessStartInfo start = new ProcessStartInfo();
//path to Python program
start.FileName = @"F:\Python\Python35-32\python.exe";
start.Arguments = string.Format("{0} ", args);
//very important to use modules and other scripts called by main script
start.WorkingDirectory = @"f:\labs";
start.UseShellExecute = false;
start.RedirectStandardOutput = true;
using (Process process = Process.Start(start))
{
using (StreamReader reader = process.StandardOutput)
{
string result = reader.ReadToEnd();
Console.Write(result);
}
}
}
}
测试脚本:
test.py
import fibo
print ( "Hello, world!")
fibo.fib(1000)
模块:fibo.py
def fib(n): # write Fibonacci series up to n
a, b = 0, 1
while b < n:
print (b),
a, b = b, a+b
我想使用 c# 调用我的 python 程序并让它在调用时自动执行。我已经完成了打开程序,但如何 运行 它并获得输出。这是我最后一年的项目,请帮助我 out.Here 是我的代码:
Process p = new Process();
ProcessStartInfo pi = new ProcessStartInfo();
pi.UseShellExecute = true;
pi.FileName = @"python.exe";
p.StartInfo = pi;
try
{
p.StandardOutput.ReadToEnd();
}
catch (Exception Ex)
{
}
以下代码执行 python 调用模块的脚本和 return 结果
class Program
{
static void Main(string[] args)
{
RunPython();
Console.ReadKey();
}
static void RunPython()
{
var args = "test.py"; //main python script
ProcessStartInfo start = new ProcessStartInfo();
//path to Python program
start.FileName = @"F:\Python\Python35-32\python.exe";
start.Arguments = string.Format("{0} ", args);
//very important to use modules and other scripts called by main script
start.WorkingDirectory = @"f:\labs";
start.UseShellExecute = false;
start.RedirectStandardOutput = true;
using (Process process = Process.Start(start))
{
using (StreamReader reader = process.StandardOutput)
{
string result = reader.ReadToEnd();
Console.Write(result);
}
}
}
}
测试脚本:
test.py
import fibo
print ( "Hello, world!")
fibo.fib(1000)
模块:fibo.py
def fib(n): # write Fibonacci series up to n
a, b = 0, 1
while b < n:
print (b),
a, b = b, a+b