我正在尝试从C#执行python脚本。我在以下链接的另一篇文章中找到了实现此目的的方法:run a python script from c#。但是,当进程到达使用(Process process = Process.Start(start))
行时,我收到错误。以下是我正在实施的代码:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RunPy
{
class Program
{
static void Main(string[] args)
{
// As an example, cmd would be @C:/Python26/python.exe and args would be C://Python26//test.py 100
String cmd = "@C:/Program Files (x86)/Python27/python.exe";
String argss = "C:/My_Python_lib/happyBirthday.py 'joe'";
// Console.Write(argss); this line is just to test the output of the above argss
// Console.ReadLine(); this line goes with the above line to prevent the window from closing so fast
run_cmd(cmd, argss);
//ProcessStartInfo startInfo = new ProcessStartInfo();
//startInfo.FileName = cmd;
//Process.Start(cmd);
}
private static void run_cmd(string cmd, string args)
{
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = cmd;
start.Arguments = 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);
}
}
}
}
}
以下是我要回复的错误:
“System.ComponentModel.Win32Exception”类型的未处理异常 发生在System.dll
中
任何帮助将不胜感激。谢谢!
答案 0 :(得分:2)
您错误地初始化了cmd
变量。 “@”应该在引号之前(即@“C:/ ...”)。当然,使用正斜杠而不是反斜杠无论如何都不需要逐字字符串,所以你可以完全省略“@”。
String cmd = "C:/Program Files (x86)/Python27/python.exe";
答案 1 :(得分:0)
试试
string cmd = @"C:\Program Files (x86)\Python27\python.exe";
或
string cmd = @"C:\PROGRA~1\Python27\python.exe";
答案 2 :(得分:0)
首先读取python exe并将其加载到内存中。
var assembly = Assembly.GetExecutingAssembly();
var resourcePath = assembly.GetManifestResourceNames().Single(str => str.EndsWith("python.exe"));
FileStream outputFileStream = new FileStream(Path.Combine(Directory.GetCurrentDirectory(), resourcePath), FileMode.OpenOrCreate, FileAccess.ReadWrite);
using (Stream stream = assembly.GetManifestResourceStream(resourcePath))
{
if (stream != null)
{
stream.CopyTo(outputFileStream);
stream.Close();
}
outputFileStream.Close();
}