python - 如何从一个脚本打开两个控制台

标签 python python-2.7

除了脚本自己的控制台(什么也不做)我想打开两个控制台并以不同的方式打印变量con1con2控制台,我怎样才能实现这一目标。

con1 = 'This is Console1'
con2 = 'This is Console2'

我不知道如何实现这一目标,并花了几个小时尝试使用 subprocess 等模块来实现此目的,但没有成功。顺便说一句,我在 Windows 上。

<小时/>

编辑:

threading 模块可以完成这项工作吗?或者是否需要多处理

例如:

enter image description here

最佳答案

如果你不想reconsider your problem and use a GUI例如 @Kevin's answer然后您可以使用 subprocess 模块同时启动两个新控制台并在打开的窗口中显示两个给定的字符串:

#!/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的简化版本:

#!/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()

关于python - 如何从一个脚本打开两个控制台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53208336/

相关文章:

python - 如何在Scrapy中实现自定义dupefilter?

python - 如何使用正则表达式解析角度值

python - 如何使用 py.test 在 setup.py 上避免 "No commands supplied"

python - 当只有 1 行时,数组的形状和 __len__ 返回 4?

python - 为什么 Ruby 有 Rails 而 Python 没有中央框架?

macos - 在 Mac 上安装 PySide : is there a working method?

python - AppEngine id/key/from_path 很困惑我应该使用什么

python - 列出 max() 方法

python-2.7 - Python 错误 - Google Foobar

Python:运行 SimpleHTTPServer 并在脚本中向它发出请求