How can I open two consoles from a single script
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'
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.
Edit:
Would the threading
module do the job? or is multiprocessing
needed?
Eg:
python python-2.7
|
show 11 more comments
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'
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.
Edit:
Would the threading
module do the job? or is multiprocessing
needed?
Eg:
python python-2.7
1
there is only one console
– Andreas Jung
Oct 20 '13 at 15:57
2
it is really possible
– Kroltan
Oct 20 '13 at 16:01
1
You can have one script that starts itself as a new subprocess, or you could get a native lib. But you definitely can do it.
– Kroltan
Oct 20 '13 at 16:05
1
This might be helpful: stackoverflow.com/questions/11621991/open-second-python-console (possible duplicate)
– Chris Laplante
Oct 20 '13 at 16:05
3
Any specific OS?
– Bleeding Fingers
Oct 20 '13 at 16:37
|
show 11 more comments
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'
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.
Edit:
Would the threading
module do the job? or is multiprocessing
needed?
Eg:
python python-2.7
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'
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.
Edit:
Would the threading
module do the job? or is multiprocessing
needed?
Eg:
python python-2.7
python python-2.7
edited Nov 7 '13 at 11:05
K DawG
asked Oct 20 '13 at 15:56
K DawGK DawG
6,82682357
6,82682357
1
there is only one console
– Andreas Jung
Oct 20 '13 at 15:57
2
it is really possible
– Kroltan
Oct 20 '13 at 16:01
1
You can have one script that starts itself as a new subprocess, or you could get a native lib. But you definitely can do it.
– Kroltan
Oct 20 '13 at 16:05
1
This might be helpful: stackoverflow.com/questions/11621991/open-second-python-console (possible duplicate)
– Chris Laplante
Oct 20 '13 at 16:05
3
Any specific OS?
– Bleeding Fingers
Oct 20 '13 at 16:37
|
show 11 more comments
1
there is only one console
– Andreas Jung
Oct 20 '13 at 15:57
2
it is really possible
– Kroltan
Oct 20 '13 at 16:01
1
You can have one script that starts itself as a new subprocess, or you could get a native lib. But you definitely can do it.
– Kroltan
Oct 20 '13 at 16:05
1
This might be helpful: stackoverflow.com/questions/11621991/open-second-python-console (possible duplicate)
– Chris Laplante
Oct 20 '13 at 16:05
3
Any specific OS?
– Bleeding Fingers
Oct 20 '13 at 16:37
1
1
there is only one console
– Andreas Jung
Oct 20 '13 at 15:57
there is only one console
– Andreas Jung
Oct 20 '13 at 15:57
2
2
it is really possible
– Kroltan
Oct 20 '13 at 16:01
it is really possible
– Kroltan
Oct 20 '13 at 16:01
1
1
You can have one script that starts itself as a new subprocess, or you could get a native lib. But you definitely can do it.
– Kroltan
Oct 20 '13 at 16:05
You can have one script that starts itself as a new subprocess, or you could get a native lib. But you definitely can do it.
– Kroltan
Oct 20 '13 at 16:05
1
1
This might be helpful: stackoverflow.com/questions/11621991/open-second-python-console (possible duplicate)
– Chris Laplante
Oct 20 '13 at 16:05
This might be helpful: stackoverflow.com/questions/11621991/open-second-python-console (possible duplicate)
– Chris Laplante
Oct 20 '13 at 16:05
3
3
Any specific OS?
– Bleeding Fingers
Oct 20 '13 at 16:37
Any specific OS?
– Bleeding Fingers
Oct 20 '13 at 16:37
|
show 11 more comments
6 Answers
6
active
oldest
votes
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("byen")
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()
1
why doesn't it display any text?
– K DawG
Nov 6 '13 at 10:30
@KDawG: I've tested it on Python 3.3 windows 8. It works as written: two consoles pop up with the messages and they are closed in 10 seconds. The code should work without changes on Python 2.7
– jfs
Nov 6 '13 at 19:00
Windows 7 user here. When I run this, two console windows flash on screen and quickly close. Ten seconds later, I getOSError: [Errno 22] Invalid argument
. (see full stack trace here)
– Kevin
Nov 7 '13 at 20:53
@Kevin: How do you run the script? Could you try: 1. Open a console in a directory with the script 2. Runpy the_script.py
– jfs
Nov 8 '13 at 5:38
Yes, the result is the same.
– Kevin
Nov 8 '13 at 12:57
|
show 7 more comments
You can get something like two consoles using two Tkinter Text widgets.
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")
Result:
add a comment |
I don't know if it suits you, but you can open two Python interpreters using Windows start
command:
from subprocess import Popen
p1 = Popen('start c:python27python.exe', shell=True)
p2 = Popen('start c:python27python.exe', shell=True)
Of course there is problem that now Python runs in interactive mode which is not what u want (you can also pass file as parameter and that file will be executed).
On Linux I would try to make named pipe, pass the name of the file to python.exe and write python commands to that file. 'Maybe' it will work ;)
But I don't have an idea how to create named pipe on Windows. Windows API ... (fill urself).
You saved my day
– Vasilly.Prokopyev
Dec 11 '14 at 11:10
add a comment |
pymux
pymux gets close to what you want: https://github.com/jonathanslenders/pymux
Unfortunately it is mostly a CLI tool replacement for tmux
and does not have a decent programmatic API.
But hacking it up to expose that API is likely the most robust option if you are serious about this.
add a comment |
I used jfs' response. Here is my embellishment/theft of jfs response.
This is tailored to run on Win10 and also handles Unicode:
# https://stackoverflow.com/questions/19479504/how-can-i-open-two-consoles-from-a-single-script
import sys, time, os, locale
from subprocess import Popen, PIPE, CREATE_NEW_CONSOLE
class console(Popen) :
NumConsoles = 0
def __init__(self, color=None, title=None):
console.NumConsoles += 1
cmd = "import sys, os, locale"
cmd += "nos.system('color " + color + "')" if color is not None else ""
title = title if title is not None else "console #" + str(console.NumConsoles)
cmd += "nos.system("title " + title + "")"
# poor man's `cat`
cmd += """
print(sys.stdout.encoding, locale.getpreferredencoding() )
endcoding = locale.getpreferredencoding()
for line in sys.stdin:
sys.stdout.buffer.write(line.encode(endcoding))
sys.stdout.flush()
"""
cmd = sys.executable, "-c", cmd
# print(cmd, end="", flush=True)
super().__init__(cmd, stdin=PIPE, bufsize=1, universal_newlines=True, creationflags=CREATE_NEW_CONSOLE, encoding='utf-8')
def write(self, msg):
self.stdin.write(msg + "n" )
if __name__ == "__main__":
myConsole = console(color="c0", title="test error console")
myConsole.write("Thank you jfs. Cool explanation")
NoTitle= console()
NoTitle.write("default color and title! This answer uses Windows 10")
NoTitle.write(u"♥♥♥♥♥♥♥♥")
NoTitle.write("♥")
time.sleep(5)
myConsole.terminate()
NoTitle.write("some more text. Run this at the python console.")
time.sleep(4)
NoTitle.terminate()
time.sleep(5)
add a comment |
Do you know about screen/tmux?
How about tmuxp? For example, you can try to run cat
in split panes and use "sendkeys" to send output (but dig the docs, may be there is even easier ways to achieve this).
As a side bonus this will work in the text console or GUI.
1
Working example please....
– K DawG
Nov 5 '13 at 17:52
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f19479504%2fhow-can-i-open-two-consoles-from-a-single-script%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
6 Answers
6
active
oldest
votes
6 Answers
6
active
oldest
votes
active
oldest
votes
active
oldest
votes
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("byen")
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()
1
why doesn't it display any text?
– K DawG
Nov 6 '13 at 10:30
@KDawG: I've tested it on Python 3.3 windows 8. It works as written: two consoles pop up with the messages and they are closed in 10 seconds. The code should work without changes on Python 2.7
– jfs
Nov 6 '13 at 19:00
Windows 7 user here. When I run this, two console windows flash on screen and quickly close. Ten seconds later, I getOSError: [Errno 22] Invalid argument
. (see full stack trace here)
– Kevin
Nov 7 '13 at 20:53
@Kevin: How do you run the script? Could you try: 1. Open a console in a directory with the script 2. Runpy the_script.py
– jfs
Nov 8 '13 at 5:38
Yes, the result is the same.
– Kevin
Nov 8 '13 at 12:57
|
show 7 more comments
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("byen")
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()
1
why doesn't it display any text?
– K DawG
Nov 6 '13 at 10:30
@KDawG: I've tested it on Python 3.3 windows 8. It works as written: two consoles pop up with the messages and they are closed in 10 seconds. The code should work without changes on Python 2.7
– jfs
Nov 6 '13 at 19:00
Windows 7 user here. When I run this, two console windows flash on screen and quickly close. Ten seconds later, I getOSError: [Errno 22] Invalid argument
. (see full stack trace here)
– Kevin
Nov 7 '13 at 20:53
@Kevin: How do you run the script? Could you try: 1. Open a console in a directory with the script 2. Runpy the_script.py
– jfs
Nov 8 '13 at 5:38
Yes, the result is the same.
– Kevin
Nov 8 '13 at 12:57
|
show 7 more comments
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("byen")
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()
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("byen")
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()
edited May 23 '17 at 12:10
Community♦
11
11
answered Nov 5 '13 at 19:49
jfsjfs
265k815611100
265k815611100
1
why doesn't it display any text?
– K DawG
Nov 6 '13 at 10:30
@KDawG: I've tested it on Python 3.3 windows 8. It works as written: two consoles pop up with the messages and they are closed in 10 seconds. The code should work without changes on Python 2.7
– jfs
Nov 6 '13 at 19:00
Windows 7 user here. When I run this, two console windows flash on screen and quickly close. Ten seconds later, I getOSError: [Errno 22] Invalid argument
. (see full stack trace here)
– Kevin
Nov 7 '13 at 20:53
@Kevin: How do you run the script? Could you try: 1. Open a console in a directory with the script 2. Runpy the_script.py
– jfs
Nov 8 '13 at 5:38
Yes, the result is the same.
– Kevin
Nov 8 '13 at 12:57
|
show 7 more comments
1
why doesn't it display any text?
– K DawG
Nov 6 '13 at 10:30
@KDawG: I've tested it on Python 3.3 windows 8. It works as written: two consoles pop up with the messages and they are closed in 10 seconds. The code should work without changes on Python 2.7
– jfs
Nov 6 '13 at 19:00
Windows 7 user here. When I run this, two console windows flash on screen and quickly close. Ten seconds later, I getOSError: [Errno 22] Invalid argument
. (see full stack trace here)
– Kevin
Nov 7 '13 at 20:53
@Kevin: How do you run the script? Could you try: 1. Open a console in a directory with the script 2. Runpy the_script.py
– jfs
Nov 8 '13 at 5:38
Yes, the result is the same.
– Kevin
Nov 8 '13 at 12:57
1
1
why doesn't it display any text?
– K DawG
Nov 6 '13 at 10:30
why doesn't it display any text?
– K DawG
Nov 6 '13 at 10:30
@KDawG: I've tested it on Python 3.3 windows 8. It works as written: two consoles pop up with the messages and they are closed in 10 seconds. The code should work without changes on Python 2.7
– jfs
Nov 6 '13 at 19:00
@KDawG: I've tested it on Python 3.3 windows 8. It works as written: two consoles pop up with the messages and they are closed in 10 seconds. The code should work without changes on Python 2.7
– jfs
Nov 6 '13 at 19:00
Windows 7 user here. When I run this, two console windows flash on screen and quickly close. Ten seconds later, I get
OSError: [Errno 22] Invalid argument
. (see full stack trace here)– Kevin
Nov 7 '13 at 20:53
Windows 7 user here. When I run this, two console windows flash on screen and quickly close. Ten seconds later, I get
OSError: [Errno 22] Invalid argument
. (see full stack trace here)– Kevin
Nov 7 '13 at 20:53
@Kevin: How do you run the script? Could you try: 1. Open a console in a directory with the script 2. Run
py the_script.py
– jfs
Nov 8 '13 at 5:38
@Kevin: How do you run the script? Could you try: 1. Open a console in a directory with the script 2. Run
py the_script.py
– jfs
Nov 8 '13 at 5:38
Yes, the result is the same.
– Kevin
Nov 8 '13 at 12:57
Yes, the result is the same.
– Kevin
Nov 8 '13 at 12:57
|
show 7 more comments
You can get something like two consoles using two Tkinter Text widgets.
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")
Result:
add a comment |
You can get something like two consoles using two Tkinter Text widgets.
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")
Result:
add a comment |
You can get something like two consoles using two Tkinter Text widgets.
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")
Result:
You can get something like two consoles using two Tkinter Text widgets.
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")
Result:
answered Nov 5 '13 at 18:27
KevinKevin
58.3k1168112
58.3k1168112
add a comment |
add a comment |
I don't know if it suits you, but you can open two Python interpreters using Windows start
command:
from subprocess import Popen
p1 = Popen('start c:python27python.exe', shell=True)
p2 = Popen('start c:python27python.exe', shell=True)
Of course there is problem that now Python runs in interactive mode which is not what u want (you can also pass file as parameter and that file will be executed).
On Linux I would try to make named pipe, pass the name of the file to python.exe and write python commands to that file. 'Maybe' it will work ;)
But I don't have an idea how to create named pipe on Windows. Windows API ... (fill urself).
You saved my day
– Vasilly.Prokopyev
Dec 11 '14 at 11:10
add a comment |
I don't know if it suits you, but you can open two Python interpreters using Windows start
command:
from subprocess import Popen
p1 = Popen('start c:python27python.exe', shell=True)
p2 = Popen('start c:python27python.exe', shell=True)
Of course there is problem that now Python runs in interactive mode which is not what u want (you can also pass file as parameter and that file will be executed).
On Linux I would try to make named pipe, pass the name of the file to python.exe and write python commands to that file. 'Maybe' it will work ;)
But I don't have an idea how to create named pipe on Windows. Windows API ... (fill urself).
You saved my day
– Vasilly.Prokopyev
Dec 11 '14 at 11:10
add a comment |
I don't know if it suits you, but you can open two Python interpreters using Windows start
command:
from subprocess import Popen
p1 = Popen('start c:python27python.exe', shell=True)
p2 = Popen('start c:python27python.exe', shell=True)
Of course there is problem that now Python runs in interactive mode which is not what u want (you can also pass file as parameter and that file will be executed).
On Linux I would try to make named pipe, pass the name of the file to python.exe and write python commands to that file. 'Maybe' it will work ;)
But I don't have an idea how to create named pipe on Windows. Windows API ... (fill urself).
I don't know if it suits you, but you can open two Python interpreters using Windows start
command:
from subprocess import Popen
p1 = Popen('start c:python27python.exe', shell=True)
p2 = Popen('start c:python27python.exe', shell=True)
Of course there is problem that now Python runs in interactive mode which is not what u want (you can also pass file as parameter and that file will be executed).
On Linux I would try to make named pipe, pass the name of the file to python.exe and write python commands to that file. 'Maybe' it will work ;)
But I don't have an idea how to create named pipe on Windows. Windows API ... (fill urself).
answered Nov 9 '13 at 22:54
marxinmarxin
1,62332436
1,62332436
You saved my day
– Vasilly.Prokopyev
Dec 11 '14 at 11:10
add a comment |
You saved my day
– Vasilly.Prokopyev
Dec 11 '14 at 11:10
You saved my day
– Vasilly.Prokopyev
Dec 11 '14 at 11:10
You saved my day
– Vasilly.Prokopyev
Dec 11 '14 at 11:10
add a comment |
pymux
pymux gets close to what you want: https://github.com/jonathanslenders/pymux
Unfortunately it is mostly a CLI tool replacement for tmux
and does not have a decent programmatic API.
But hacking it up to expose that API is likely the most robust option if you are serious about this.
add a comment |
pymux
pymux gets close to what you want: https://github.com/jonathanslenders/pymux
Unfortunately it is mostly a CLI tool replacement for tmux
and does not have a decent programmatic API.
But hacking it up to expose that API is likely the most robust option if you are serious about this.
add a comment |
pymux
pymux gets close to what you want: https://github.com/jonathanslenders/pymux
Unfortunately it is mostly a CLI tool replacement for tmux
and does not have a decent programmatic API.
But hacking it up to expose that API is likely the most robust option if you are serious about this.
pymux
pymux gets close to what you want: https://github.com/jonathanslenders/pymux
Unfortunately it is mostly a CLI tool replacement for tmux
and does not have a decent programmatic API.
But hacking it up to expose that API is likely the most robust option if you are serious about this.
answered Aug 29 '18 at 7:59
Ciro Santilli 新疆改造中心 六四事件 法轮功Ciro Santilli 新疆改造中心 六四事件 法轮功
141k33542458
141k33542458
add a comment |
add a comment |
I used jfs' response. Here is my embellishment/theft of jfs response.
This is tailored to run on Win10 and also handles Unicode:
# https://stackoverflow.com/questions/19479504/how-can-i-open-two-consoles-from-a-single-script
import sys, time, os, locale
from subprocess import Popen, PIPE, CREATE_NEW_CONSOLE
class console(Popen) :
NumConsoles = 0
def __init__(self, color=None, title=None):
console.NumConsoles += 1
cmd = "import sys, os, locale"
cmd += "nos.system('color " + color + "')" if color is not None else ""
title = title if title is not None else "console #" + str(console.NumConsoles)
cmd += "nos.system("title " + title + "")"
# poor man's `cat`
cmd += """
print(sys.stdout.encoding, locale.getpreferredencoding() )
endcoding = locale.getpreferredencoding()
for line in sys.stdin:
sys.stdout.buffer.write(line.encode(endcoding))
sys.stdout.flush()
"""
cmd = sys.executable, "-c", cmd
# print(cmd, end="", flush=True)
super().__init__(cmd, stdin=PIPE, bufsize=1, universal_newlines=True, creationflags=CREATE_NEW_CONSOLE, encoding='utf-8')
def write(self, msg):
self.stdin.write(msg + "n" )
if __name__ == "__main__":
myConsole = console(color="c0", title="test error console")
myConsole.write("Thank you jfs. Cool explanation")
NoTitle= console()
NoTitle.write("default color and title! This answer uses Windows 10")
NoTitle.write(u"♥♥♥♥♥♥♥♥")
NoTitle.write("♥")
time.sleep(5)
myConsole.terminate()
NoTitle.write("some more text. Run this at the python console.")
time.sleep(4)
NoTitle.terminate()
time.sleep(5)
add a comment |
I used jfs' response. Here is my embellishment/theft of jfs response.
This is tailored to run on Win10 and also handles Unicode:
# https://stackoverflow.com/questions/19479504/how-can-i-open-two-consoles-from-a-single-script
import sys, time, os, locale
from subprocess import Popen, PIPE, CREATE_NEW_CONSOLE
class console(Popen) :
NumConsoles = 0
def __init__(self, color=None, title=None):
console.NumConsoles += 1
cmd = "import sys, os, locale"
cmd += "nos.system('color " + color + "')" if color is not None else ""
title = title if title is not None else "console #" + str(console.NumConsoles)
cmd += "nos.system("title " + title + "")"
# poor man's `cat`
cmd += """
print(sys.stdout.encoding, locale.getpreferredencoding() )
endcoding = locale.getpreferredencoding()
for line in sys.stdin:
sys.stdout.buffer.write(line.encode(endcoding))
sys.stdout.flush()
"""
cmd = sys.executable, "-c", cmd
# print(cmd, end="", flush=True)
super().__init__(cmd, stdin=PIPE, bufsize=1, universal_newlines=True, creationflags=CREATE_NEW_CONSOLE, encoding='utf-8')
def write(self, msg):
self.stdin.write(msg + "n" )
if __name__ == "__main__":
myConsole = console(color="c0", title="test error console")
myConsole.write("Thank you jfs. Cool explanation")
NoTitle= console()
NoTitle.write("default color and title! This answer uses Windows 10")
NoTitle.write(u"♥♥♥♥♥♥♥♥")
NoTitle.write("♥")
time.sleep(5)
myConsole.terminate()
NoTitle.write("some more text. Run this at the python console.")
time.sleep(4)
NoTitle.terminate()
time.sleep(5)
add a comment |
I used jfs' response. Here is my embellishment/theft of jfs response.
This is tailored to run on Win10 and also handles Unicode:
# https://stackoverflow.com/questions/19479504/how-can-i-open-two-consoles-from-a-single-script
import sys, time, os, locale
from subprocess import Popen, PIPE, CREATE_NEW_CONSOLE
class console(Popen) :
NumConsoles = 0
def __init__(self, color=None, title=None):
console.NumConsoles += 1
cmd = "import sys, os, locale"
cmd += "nos.system('color " + color + "')" if color is not None else ""
title = title if title is not None else "console #" + str(console.NumConsoles)
cmd += "nos.system("title " + title + "")"
# poor man's `cat`
cmd += """
print(sys.stdout.encoding, locale.getpreferredencoding() )
endcoding = locale.getpreferredencoding()
for line in sys.stdin:
sys.stdout.buffer.write(line.encode(endcoding))
sys.stdout.flush()
"""
cmd = sys.executable, "-c", cmd
# print(cmd, end="", flush=True)
super().__init__(cmd, stdin=PIPE, bufsize=1, universal_newlines=True, creationflags=CREATE_NEW_CONSOLE, encoding='utf-8')
def write(self, msg):
self.stdin.write(msg + "n" )
if __name__ == "__main__":
myConsole = console(color="c0", title="test error console")
myConsole.write("Thank you jfs. Cool explanation")
NoTitle= console()
NoTitle.write("default color and title! This answer uses Windows 10")
NoTitle.write(u"♥♥♥♥♥♥♥♥")
NoTitle.write("♥")
time.sleep(5)
myConsole.terminate()
NoTitle.write("some more text. Run this at the python console.")
time.sleep(4)
NoTitle.terminate()
time.sleep(5)
I used jfs' response. Here is my embellishment/theft of jfs response.
This is tailored to run on Win10 and also handles Unicode:
# https://stackoverflow.com/questions/19479504/how-can-i-open-two-consoles-from-a-single-script
import sys, time, os, locale
from subprocess import Popen, PIPE, CREATE_NEW_CONSOLE
class console(Popen) :
NumConsoles = 0
def __init__(self, color=None, title=None):
console.NumConsoles += 1
cmd = "import sys, os, locale"
cmd += "nos.system('color " + color + "')" if color is not None else ""
title = title if title is not None else "console #" + str(console.NumConsoles)
cmd += "nos.system("title " + title + "")"
# poor man's `cat`
cmd += """
print(sys.stdout.encoding, locale.getpreferredencoding() )
endcoding = locale.getpreferredencoding()
for line in sys.stdin:
sys.stdout.buffer.write(line.encode(endcoding))
sys.stdout.flush()
"""
cmd = sys.executable, "-c", cmd
# print(cmd, end="", flush=True)
super().__init__(cmd, stdin=PIPE, bufsize=1, universal_newlines=True, creationflags=CREATE_NEW_CONSOLE, encoding='utf-8')
def write(self, msg):
self.stdin.write(msg + "n" )
if __name__ == "__main__":
myConsole = console(color="c0", title="test error console")
myConsole.write("Thank you jfs. Cool explanation")
NoTitle= console()
NoTitle.write("default color and title! This answer uses Windows 10")
NoTitle.write(u"♥♥♥♥♥♥♥♥")
NoTitle.write("♥")
time.sleep(5)
myConsole.terminate()
NoTitle.write("some more text. Run this at the python console.")
time.sleep(4)
NoTitle.terminate()
time.sleep(5)
edited Nov 25 '18 at 2:04
answered Nov 23 '18 at 21:54
JDOaktownJDOaktown
70421629
70421629
add a comment |
add a comment |
Do you know about screen/tmux?
How about tmuxp? For example, you can try to run cat
in split panes and use "sendkeys" to send output (but dig the docs, may be there is even easier ways to achieve this).
As a side bonus this will work in the text console or GUI.
1
Working example please....
– K DawG
Nov 5 '13 at 17:52
add a comment |
Do you know about screen/tmux?
How about tmuxp? For example, you can try to run cat
in split panes and use "sendkeys" to send output (but dig the docs, may be there is even easier ways to achieve this).
As a side bonus this will work in the text console or GUI.
1
Working example please....
– K DawG
Nov 5 '13 at 17:52
add a comment |
Do you know about screen/tmux?
How about tmuxp? For example, you can try to run cat
in split panes and use "sendkeys" to send output (but dig the docs, may be there is even easier ways to achieve this).
As a side bonus this will work in the text console or GUI.
Do you know about screen/tmux?
How about tmuxp? For example, you can try to run cat
in split panes and use "sendkeys" to send output (but dig the docs, may be there is even easier ways to achieve this).
As a side bonus this will work in the text console or GUI.
answered Nov 5 '13 at 17:48
Paulo ScardinePaulo Scardine
39.6k889117
39.6k889117
1
Working example please....
– K DawG
Nov 5 '13 at 17:52
add a comment |
1
Working example please....
– K DawG
Nov 5 '13 at 17:52
1
1
Working example please....
– K DawG
Nov 5 '13 at 17:52
Working example please....
– K DawG
Nov 5 '13 at 17:52
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f19479504%2fhow-can-i-open-two-consoles-from-a-single-script%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
there is only one console
– Andreas Jung
Oct 20 '13 at 15:57
2
it is really possible
– Kroltan
Oct 20 '13 at 16:01
1
You can have one script that starts itself as a new subprocess, or you could get a native lib. But you definitely can do it.
– Kroltan
Oct 20 '13 at 16:05
1
This might be helpful: stackoverflow.com/questions/11621991/open-second-python-console (possible duplicate)
– Chris Laplante
Oct 20 '13 at 16:05
3
Any specific OS?
– Bleeding Fingers
Oct 20 '13 at 16:37