[英]Error when trying to start python.exe from C#
我正在尝试从 C# 执行 python 脚本。 我在以下链接的另一篇文章中找到了一种方法来完成此操作: run a python script from c# 。 但是,当进程到达 using (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.dll 中发生类型为“System.ComponentModel.Win32Exception”的未处理异常
任何帮助将不胜感激。 谢谢!
您错误地初始化了cmd
变量。 "@" 应该在引号之前(即@"C:/...")。 当然,使用正斜杠而不是反斜杠无论如何都不需要逐字字符串,因此您可以完全省略“@”。
String cmd = "C:/Program Files (x86)/Python27/python.exe";
试试看
string cmd = @"C:\Program Files (x86)\Python27\python.exe";
或
string cmd = @"C:\PROGRA~1\Python27\python.exe";
首先读取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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.