[英]How to print output of python script to Windows console, when running via batch file?
[英]How to show console output when running a python script from another python file
我正在制作一个带有文本框和运行按钮的简单IDE。 这要求用户输入文件名,将代码写入文件并运行该文件。 我想显示从控制台输出的任何内容,例如打印,输入等。就像IDE一样。 这可能吗?
这是我的代码:
from Tkinter import *
import tkFileDialog
import ScrolledText
import subprocess
filepath=""
def run():
global filepath
print "<<<<<<=====-------------Restart-------------=====>>>>>>"
py=code.get(1.0,END)
if filepath=="":
filepath=tkFileDialog.asksaveasfilename()
if ".py" not in filepath:
filepath=filepath+".py"
script=open(filepath, "w")
script.write(py)
script.close()
p = subprocess.Popen(['python', filepath],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
for line in iter(p.stdout.readline, ''):
print line
print "<<<<<<=====-------------EXECUTION FINISHED-------------=====>>>>>>"
root = Tk()
code=ScrolledText.ScrolledText(root)
code.pack()
run=Button(root,text="Run", command=run)
run.pack()
root.mainloop()
是的,只需使用子流程模块。
一站式获取输出
import subprocess
output = subprocess.check_output(['python', filepath])
如果要从调用的流程中捕获标准错误以及从标准过程中捕获标准错误,请改用此方法:
output = subprocess.check_output(['python', filepath], stderr=subprocess.STDOUT)
或者,如果您想分别捕获它们:
p = subprocess.Popen(['python', filepath],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
out, err = p.communicate()
获得产生的输出
这将逐行为您提供组合的stdout和strerr输出:
p = subprocess.Popen(['python', filepath],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
for line in iter(p.stdout.readline, ''):
# process the line
保持UI响应
如果在与GUI相同的线程上运行上述代码,则实际上是在等待每一行时阻止Tk的事件循环运行。 这意味着,尽管您实时获取每行并将其写入到GUI,但直到事件循环再次运行并处理所有对Tk的调用之前,它不会更新显示。
您需要在新线程上运行子流程代码,并在GUI线程中定期检查是否有新输入。
我为您做了一个基于您的示例,您可以在这里找到它:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.