我有以下小python脚本来运行本地服务器来测试一些html:
print('opened')
from http.server import HTTPServer, SimpleHTTPRequestHandler
server_address = ('', 8000)
httpd = HTTPServer(server_address, SimpleHTTPRequestHandler)
print("Listening at https://127.0.0.1:8000/ . . .")
httpd.serve_forever()
Run Code Online (Sandbox Code Playgroud)
当我在终端中运行它时,它会阻止print语句:没有打印.但服务器工作,我可以localhost:8000在浏览器中访问我的html文件.但是,如果我注释掉最后一行,则调用serve_forever(),它可以打印"打开"和"收听https:127.0.0.1:8000 /"..'.当然,它实际上并不起作用,因为现在服务器没有运行.
我觉得这很混乱.前一行在最后一行之前执行.为什么最后一行会导致前一行不起作用?
Windows7上的Python3,如果有人要问,但我怀疑这是相关的.
我想从 Node.js 应用程序(具体来说是 Electron.js)中执行 Python 脚本。我想在生成后立即显示输出。Python 脚本很大,需要花费大量时间来处理,但它会定期输出数据。
我已经使用python-shell和child_process尝试过此操作。但是,当我执行 Python 文件时,仅当程序结束时才会显示输出。
我认为这可以使用shell.on('message',function(){})or来完成scriptExecution.stdout.on('data',function()),但显然情况并非如此。
这可能吗?我该怎么做?也许使用其他方式...
我正在尝试编写一个 C# 程序来捕获 python 程序中的标准输出。我的问题是所有输出都在程序执行之后而不是实际发生时出现。例如,对于这个 python 程序:
print "Hello"
time.sleep(2)
print "Hello"
Run Code Online (Sandbox Code Playgroud)
我希望得到“你好”,两秒钟的间隔,然后是另一个“你好”。实际结果是两秒钟的间隔,然后是“你好”,“你好”。
如果我从命令行运行上面的 python 脚本,我会得到所需的行为。如果命令提示符可以执行此操作,那么我应该能够模拟该功能而不必重复刷新缓冲区。
我正在使用它从 C# 运行该过程:
_proc = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "C:\\Python27\\python.exe",
Arguments = pyScript,
RedirectStandardError = true,
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
}
};
_proc.OutputDataReceived += ProcOnOutputDataReceived;
_proc.Start();
_proc.BeginOutputReadLine();
Run Code Online (Sandbox Code Playgroud)
我可以运行这个 C# 代码(并更改上面的 ProcessStartInfo 属性以运行 C# 可执行文件)并且它的行为正确:
Console.WriteLine("Hello");
Thread.Sleep(2000);
Console.WriteLine("Hello");
Run Code Online (Sandbox Code Playgroud)
有了这个代码,我得到了“你好”,两秒钟的差距,然后是另一个“你好”。
知道为什么吗?我怎样才能让python解释器在发生时发送标准输出?
我正在尝试从 C# 运行一个 python 脚本,我想逐行而不是最后获得输出。我觉得我错过了一些重要的东西,但不知道是什么。这是我到目前为止:
static void Main(string[] args)
{
var cmd = "C:/Users/user/Documents/script.py";
var process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "C:/Users/user/AppData/Local/Programs/Python/Python36/python.exe",
Arguments = cmd,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
},
EnableRaisingEvents = true
};
process.ErrorDataReceived += Process_OutputDataReceived;
process.OutputDataReceived += Process_OutputDataReceived;
process.Start();
process.BeginErrorReadLine();
process.BeginOutputReadLine();
process.WaitForExit();
Console.Read();
}
static void Process_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
Console.WriteLine(e.Data);
}
Run Code Online (Sandbox Code Playgroud)
和python代码:
import time
for i in range(5):
print("Hello World " + …Run Code Online (Sandbox Code Playgroud) 这是我的代码:
import time as t
print('hello', end=' ')
t.sleep(1)
print('hello', end=' ')
t.sleep(1)
print('hello', end=' ')
t.sleep(1)
Run Code Online (Sandbox Code Playgroud)
我的问题是所有打印命令都在sleep命令之后执行,而这不是我的预期输出。