1

How do I get Python to start another instance of itself using subprocess? At present I have:

import subprocess
p = subprocess.Popen(["py.exe", "card game.py"])
returncode = p.wait()

However, it just opens cardgame.py in the current window.

How do I prevent this?

nunnethan
  • 15
  • 7
  • By "current window" you mean "in the same terminal window"? What's wrong with that? That's how it's supposed to be. – Aran-Fey Mar 31 '18 at 17:48
  • Yes, you're right. However, I need it to start in a separate window so that when it finishes I can catch any errors using sys.exit(1) – nunnethan Mar 31 '18 at 17:52
  • I'm sorry, what? Catching errors and terminal windows are completely unrelated things. Maybe you should add whatever problem you're having with catching errors to your question? – Aran-Fey Mar 31 '18 at 17:54
  • "card game.py" is in an whole 'try' statement. If there is an exception it goes to the "except" statement, which contains "sys.exit(1)", so main.py (the program above) can identify there is an error, and do things about it. Otherwise, main.py just exits normally. Sorry if this was not clear. – nunnethan Mar 31 '18 at 17:57
  • Ok, but you can check if the exit code of the process was 0 or 1 regardless of whether it's opened in a new terminal or not. In fact, it's _easier_ to do if they're in the same terminal window. – Aran-Fey Mar 31 '18 at 18:00
  • Oh I see! Thankyou. I was under the impression that when you used sys.exit you had to be in another window, but in fact you can see the results in the same window. Is it possible, though, to start a new instance of py.exe? – nunnethan Mar 31 '18 at 18:09
  • I think there's another misunderstanding here somewhere... yes, of course it's possible to start another instance of that. That's exactly what your code does. Are you asking how to start the game in a new terminal window? – Aran-Fey Mar 31 '18 at 18:11
  • Yes, it is. Thankyou – nunnethan Mar 31 '18 at 18:13
  • [It depends on the operating system.](https://stackoverflow.com/questions/19308415/execute-terminal-command-from-python-in-new-terminal-window) – Aran-Fey Mar 31 '18 at 18:15

1 Answers1

1

You can start another python instance by calling subprocess.call with sys.executable

import sys
import subprocess

# this will block until the card game terminates
subprocess.call([sys.executable, 'card game.py'])

or using subprocess.Popen

import sys
import subprocess

# this will not block
proc = subprocess.Popen(
    [sys.executable, 'card game.py'],
    stdout=subprocess.DEVNULL,  # if you skip these lines
    stderr=subprocess.DEVNULL,  # you must call `proc.communicate()`
)

# wait for the process to finish
proc.wait()

Read the subprocess docs.

Szabolcs Dombi
  • 5,493
  • 3
  • 39
  • 71