2

I am using python 3.6.3 and subprocess module to run another python script

#  main.py

#!/bin/env python
from subprocess import Popen,PIPE
from sys import executable

p = Popen([executable, 'test.py', 'arg1'],shell=True, stdout=PIPE)
p.wait()
print(p.stdout.read().decode())

and

#  test.py

import sys
print(sys.argv)

I expect it will run and execute test.py. However, it opens an python interpreter in interactive mode!

I tested shell=False option, it works. I tested string form rather than list form of args, it works.

I am not sure if it is a bug or not.

2
  • CPython will drop to interactive mode if it's stdin is connected to a TTY. The default of Popen is for the default io handles to be inherited, which connects the second interpreter to your TTY as well. Try passing stdin=None. Commented May 17, 2018 at 18:14
  • @user2722968 I'm unable to see that behavior with Python 3.6.5rc1. If I run python3 test.py arg1 from my terminal (where stdin is a tty), it runs the script without dropping to an interactive shell. Commented May 17, 2018 at 18:27

1 Answer 1

2

You need to remove shell=True or change the first argument to be executable + ' test.py arg1' instead of [executable, 'test.py', 'arg1'].

As explained in the documentation, with shell = True, it will run it as /bin/sh -c python test.py arg1, which means python will be run without arguments.

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

2 Comments

This is horrible and will lead to problems with more complex arguments
It is reasonable, the docs explain how it works. What can really lead to problems is using something without understanding how it works.

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.