启动Python控制台并控制其输出
我需要启动一个Python控制台,并控制它的输出。我正在使用Python的subprocess.Popen()来创建一个新的实例。
我把以下代码保存在一个Python脚本里,并从Windows命令提示符运行它。当我运行这个脚本时,它会在当前的Windows命令提示符中启动Python实例,而不是在一个单独的控制台中启动。
p = subprocess.Popen(["C:\Python31\python.exe"], shell=False,
# stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
out, _ = p.communicate()
print(out.decode())
2 个回答
1
如果你在使用Windows系统,可以利用win32console模块来为你的线程或子进程的输出打开第二个控制台。这是最简单、最方便的方法,适合在Windows上使用。
下面是一个示例代码:
import win32console
import multiprocessing
def subprocess(queue):
win32console.FreeConsole() #Frees subprocess from using main console
win32console.AllocConsole() #Creates new console and all input and output of subprocess goes to this new console
while True:
print(queue.get())
#prints any output produced by main script passed to subprocess using queue
if __name__ == "__main__":
queue = multiprocessing.Queue()
multiprocessing.Process(target=subprocess, args=[queue]).start()
while True:
print("Hello World in main console")
queue.put("Hello work in sub process console")
#sends above string to subprocess and it prints it into its console
#and whatever else you want to do in ur main process
你也可以使用线程来实现这个功能。如果你想要队列的功能,就需要使用queue模块,因为线程模块本身没有队列的功能。
2
在Windows系统中,你可以通过使用一个叫做 CREATE_NEW_CONSOLE 的创建标志,来在新的控制台会话中启动子进程。
from subprocess import Popen, CREATE_NEW_CONSOLE, PIPE
p = Popen(["C:\Python31\python.exe"], creationflags=CREATE_NEW_CONSOLE)