我正在尝试从C#运行Python脚本-当我通过cmd运行它时,它工作正常。 每当我尝试从C#运行它时,都不会得到任何print()输出。当我在python脚本中添加更多代码时,一切正常,即复制图像,...仅print()函数不起作用。
Python程序代码“ DoSomething.py”:
import time
##### MAIN #####
print("Starte Programm")
if __name__ == "__main__":
print("Programm really started...")
try:
while True:
time.sleep(0.001)
except KeyboardInterrupt:
print("Interrupted")
print("ende")
C#程序代码:
UserControl1 crtl = new UserControl1(); //Create UserControl to show Output in WPF
crtl.DataContext = this;
MyStack.Children.Add(crtl);
//Running cmd as Administrator
var pass = new SecureString();
pass.AppendChar('T');
pass.AppendChar('e');
pass.AppendChar('s');
pass.AppendChar('t');
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.WorkingDirectory = @"C:\users\admincs\";
p.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.Verb = "runas";
p.StartInfo.UserName = "admincs";
p.StartInfo.Password = pass;
p.StartInfo.Domain = "test";
//activate virtual environment for python
p.StartInfo.Arguments = @"/k ""activate deeplearning""";
p.OutputDataReceived += new DataReceivedEventHandler((sender, e) =>
{
// Prepend line numbers to each line of the output.
if (!String.IsNullOrEmpty(e.Data))
{
lineCount++;
output.Append("\n[" + lineCount + "]: " + e.Data);
_consoleOutputText = output.ToString();
}
});
p.Start();
//read the command line output
using (StreamWriter sw = p.StandardInput)
{
if (sw.BaseStream.CanWrite)
{
sw.WriteLine(@"python DoSomething.py");
}
}
// This raises OutputDataReceived events for each line of output.
p.BeginOutputReadLine();
// Write the redirected output to this application's window.
_consoleOutputText = output.ToString();
p.WaitForExit();
p.Close();