I'm trying to run a python command from within a c# process. This command is a one-liner and not a script. But strangely enough when starting the python process with the -c
flag, i.e. the command instead of script flag, I encounter some problems.
我正在尝试从c#进程中运行一个python命令。此命令是一行程序,而不是脚本。但是非常奇怪的是,在使用-c标志(即命令而不是脚本标志)启动python进程时,我遇到了一些问题。
First an example of my code that runs a script and works fine:
首先,我的代码示例运行了一个脚本,并且运行良好:
using (Process python = new Process())
{
python.StartInfo.FileName = "python";
python.StartInfo.Arguments = @"-u C:\path\to\script.py";
python.StartInfo.UseShellExecute = false;
python.StartInfo.RedirectStandardOutput = true;
python.StartInfo.RedirectStandardError = true;
python.StartInfo.CreateNoWindow = true;
python.ErrorDataReceived += Print;
python.OutputDataReceived += Print;
python.Start();
python.BeginErrorReadLine();
python.BeginOutputReadLine();
python.WaitForExit();
}
static void Print(object sender, DataReceivedEventArgs e)
{
Console.WriteLine(e.Data);
}
With the following script as an example:
以下面的脚本为例:
import time
for i in range(5):
print("Hello World " + str(i))
time.sleep(1)
The output is retrieved as it is created (not waiting until the process is finished):
在创建输出时检索输出(不等待过程完成):
Hello World 0
Hello World 1
Hello World 2
Hello World 3
Hello World 4
null
null
Then, if I change the StartInfo.Argument to "-uc 'print(1)'"
, the only two output lines I get are the null values at the end, but the 1
you would expect to retrieve from the print statement is missing:
然后,如果我将StartInfo.Argument更改为“-uc‘print(1)’”,我得到的唯一两个输出行是末尾的空值,但是您期望从print语句中检索到的1丢失了:
null
null
And lastly, if I add any space to the executing command (such as "-uc 'print(1); print(2)'"
), I get an EOL message on StdErr:
最后,如果我在执行的命令中添加任何空格(例如“-uc‘print(1);print(2)’”),我会在StdErr上收到一条EOL消息:
File "<string>", line 1
'print(1);
^
SyntaxError: EOL while scanning string literal
null
null
And for completeness; running that from the command line works just fine:
出于完整性的考虑,从命令行运行该命令非常有效:
$> python -uc 'print(1); print(2)'
1
2
Any clues how to solve both these problems?
有什么线索可以解决这两个问题吗?
更多回答
The official examples seem to use double quotes to combine arguments, maybe that makes a difference?
官方的例子似乎使用双引号来组合论点,也许这会有所不同?
I can't believe I didn't try this. It solved both problems... Thanks!
我真不敢相信我居然没试过。它解决了这两个问题。谢谢!
我是一名优秀的程序员,十分优秀!