有没有一种方法可以使用c#来执行python程序?
本文关键字:执行 python 程序 可以使 方法 一种 有没有 | 更新日期: 2023-09-27 18:02:26
我想调用我的python程序,并在调用时使用c#自动执行它。我已经做了,直到打开程序,但如何运行它,并得到输出。这是我最后一年的项目,请帮助我。下面是我的代码:
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脚本
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