gpt4 book ai didi

c# - 如何在 C# 中通过 shell 执行文件?

转载 作者:太空狗 更新时间:2023-10-29 22:13:20 25 4
gpt4 key购买 nike

我一如既往地尝试使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com