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?

9
  • By "current window" you mean "in the same terminal window"? What's wrong with that? That's how it's supposed to be. Commented Mar 31, 2018 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) Commented Mar 31, 2018 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? Commented Mar 31, 2018 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. Commented Mar 31, 2018 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. Commented Mar 31, 2018 at 18:00

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.