如何从单个脚本打开两个控制台 [英] How can I open two consoles from a single script
问题描述
除了脚本自己的控制台(什么都不做)我想打开两个控制台并以不同的方式打印变量con1
和con2
控制台,我怎样才能做到这一点.
Apart from the scripts own console (which does nothing) I want to open two consoles and print the variables con1
and con2
in different consoles, How can I achieve this.
con1 = 'This is Console1'
con2 = 'This is Console2'
我不知道如何实现这一点,并花了几个小时尝试使用诸如 subprocess
之类的模块来实现,但没有成功.顺便说一下,我在窗户上.
I've no idea how to achieve this and spent several hours trying to do so with modules such as subprocess
but with no luck. I'm on windows by the way.
threading
模块能完成这项工作吗?还是需要multiprocessing
?
Would the threading
module do the job? or is multiprocessing
needed?
例如:
推荐答案
如果您不想 重新考虑您的问题并使用GUI 例如在 @Kevin's answer 然后你可以使用 subprocess
模块来启动同时运行两个新控制台并在打开的窗口中显示两个给定的字符串:
If you don't want to reconsider your problem and use a GUI such as in @Kevin's answer then you could use subprocess
module to start two new consoles concurrently and display two given strings in the opened windows:
#!/usr/bin/env python3
import sys
import time
from subprocess import Popen, PIPE, CREATE_NEW_CONSOLE
messages = 'This is Console1', 'This is Console2'
# open new consoles
processes = [Popen([sys.executable, "-c", """import sys
for line in sys.stdin: # poor man's `cat`
sys.stdout.write(line)
sys.stdout.flush()
"""],
stdin=PIPE, bufsize=1, universal_newlines=True,
# assume the parent script is started from a console itself e.g.,
# this code is _not_ run as a *.pyw file
creationflags=CREATE_NEW_CONSOLE)
for _ in range(len(messages))]
# display messages
for proc, msg in zip(processes, messages):
proc.stdin.write(msg + "\n")
proc.stdin.flush()
time.sleep(10) # keep the windows open for a while
# close windows
for proc in processes:
proc.communicate("bye\n")
这是一个不依赖于 CREATE_NEW_CONSOLE
的简化版本:
Here's a simplified version that doesn't rely on CREATE_NEW_CONSOLE
:
#!/usr/bin/env python
"""Show messages in two new console windows simultaneously."""
import sys
import platform
from subprocess import Popen
messages = 'This is Console1', 'This is Console2'
# define a command that starts new terminal
if platform.system() == "Windows":
new_window_command = "cmd.exe /c start".split()
else: #XXX this can be made more portable
new_window_command = "x-terminal-emulator -e".split()
# open new consoles, display messages
echo = [sys.executable, "-c",
"import sys; print(sys.argv[1]); input('Press Enter..')"]
processes = [Popen(new_window_command + echo + [msg]) for msg in messages]
# wait for the windows to be closed
for proc in processes:
proc.wait()
这篇关于如何从单个脚本打开两个控制台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!