我一如既往地尝试使用 Process 类,但没有用。我所做的只是尝试运行一个 Python 文件,就像有人双击它一样。
这可能吗?
编辑:
示例代码:
string pythonScript = @"C:\callme.py";
string workDir = System.IO.Path.GetDirectoryName ( pythonScript );
Process proc = new Process ( );
proc.StartInfo.WorkingDirectory = workDir;
proc.StartInfo.UseShellExecute = true;
proc.StartInfo.FileName = pythonScript;
proc.StartInfo.Arguments = "1, 2, 3";
我没有收到任何错误,但脚本没有运行。当我手动运行脚本时,我看到了结果。
最佳答案
这是我从 C# 执行 python 脚本的代码,带有重定向的标准输入和输出(我通过标准输入传递信息),是从网上某处的示例复制而来的。如您所见,Python 位置是硬编码的,可以重构。
private static string CallPython(string script, string pyArgs, string workingDirectory, string[] standardInput)
{
ProcessStartInfo startInfo;
Process process;
string ret = "";
try
{
startInfo = new ProcessStartInfo(@"c:\python25\python.exe");
startInfo.WorkingDirectory = workingDirectory;
if (pyArgs.Length != 0)
startInfo.Arguments = script + " " + pyArgs;
else
startInfo.Arguments = script;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.RedirectStandardInput = true;
process = new Process();
process.StartInfo = startInfo;
process.Start();
// write to standard input
foreach (string si in standardInput)
{
process.StandardInput.WriteLine(si);
}
string s;
while ((s = process.StandardError.ReadLine()) != null)
{
ret += s;
throw new System.Exception(ret);
}
while ((s = process.StandardOutput.ReadLine()) != null)
{
ret += s;
}
return ret;
}
catch (System.Exception ex)
{
string problem = ex.Message;
return problem;
}
}
关于c# - 如何在 C# 中通过 shell 执行文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/749680/