我怎么能从一张纸条上打开两个控制台

2024-04-24 23:49:12 发布

您现在位置:Python中文网/ 问答频道 /正文

除了脚本自己的控制台(什么都不做)之外,我想打开两个控制台并在不同的控制台中打印变量con1con2,我如何才能实现这一点。

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

我不知道如何实现这一点,花了几个小时尝试使用诸如subprocess之类的模块来实现,但没有成功。顺便说一下,我在窗户上。


编辑:

这个threading模块会做这个工作吗?还是需要multiprocessing

例如:

enter image description here


Tags: 模块脚本编辑isthismultiprocessingsubprocess窗户
3条回答

您可以使用两个Tkinter文本小部件获得两个控制台。

from Tkinter import *
import threading

class FakeConsole(Frame):
    def __init__(self, root, *args, **kargs):
        Frame.__init__(self, root, *args, **kargs)

        #white text on black background,
        #for extra versimilitude
        self.text = Text(self, bg="black", fg="white")
        self.text.pack()

        #list of things not yet printed
        self.printQueue = []

        #one thread will be adding to the print queue, 
        #and another will be iterating through it.
        #better make sure one doesn't interfere with the other.
        self.printQueueLock = threading.Lock()

        self.after(5, self.on_idle)

    #check for new messages every five milliseconds
    def on_idle(self):
        with self.printQueueLock:
            for msg in self.printQueue:
                self.text.insert(END, msg)            
                self.text.see(END)
            self.printQueue = []
        self.after(5, self.on_idle)

    #print msg to the console
    def show(self, msg, sep="\n"):
        with self.printQueueLock:
            self.printQueue.append(str(msg) + sep)

#warning! Calling this more than once per program is a bad idea.
#Tkinter throws a fit when two roots each have a mainloop in different threads.
def makeConsoles(amount):
    root = Tk()
    consoles = [FakeConsole(root) for n in range(amount)]
    for c in consoles:
        c.pack()
    threading.Thread(target=root.mainloop).start()
    return consoles

a,b = makeConsoles(2)

a.show("This is Console 1")
b.show("This is Console 2")

a.show("I've got a lovely bunch of cocounts")
a.show("Here they are standing in a row")

b.show("Lorem ipsum dolor sit amet")
b.show("consectetur adipisicing elit")

结果:

enter image description here

我不知道它是否适合您,但您可以使用Windowsstart命令打开两个Python解释器:

from subprocess import Popen
p1 = Popen('start c:\python27\python.exe', shell=True)
p2 = Popen('start c:\python27\python.exe', shell=True)

当然,现在Python在交互模式下运行是有问题的,这不是您想要的(您还可以将文件作为参数传递,该文件将被执行)。

在Linux上,我会尝试创建命名管道,将文件名传递给python.exe,并将python命令写入该文件或许‘它会起作用;)

但我不知道如何在Windows上创建命名管道。Windows API。。。(自己填)。

如果您不想像在@Kevin's answer中那样reconsider your problem and use a GUI,那么可以使用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()

相关问题 更多 >