0

I want to use Popen from subprocess to execute the command: 'python3 test.py'

# The following is test.py code:

string = input('Enter Something')
if string == 'mypassword':
    print('Success')
else:
    print('Fail')

In my program, I want to execute 'python3 test.py' multiple times, each time supplying input, and reading the output ('Success' or 'Fail') and storing it in a variable.

My program that is suppose to execute 'python3 test.py' is as follows:

from subprocess import Popen, PIPE

# Runs test.py
command = Popen(['python3', 'test.py'], stdin=PIPE)
# After this, it prompts me to type in the input, 
# but I want to supply it from a variable

# I want to do something like
my_input = 'testpassword'
command.supplyInput(my_input)
result = command.getOutput()

# result will have the string value of 'Success' or 'Fail'
5
  • os.system(command) is used to execute the commands Commented Jul 19, 2018 at 6:24
  • I would normally use that command if I am not going to be prompted an input, but I have to follow it with an input Commented Jul 19, 2018 at 6:26
  • You can pass input as command line arguments along with the command Commented Jul 19, 2018 at 6:29
  • I understand, but in this case there aren't command line arguments. The command must be ran first, then it prompts you to manually enter something Commented Jul 19, 2018 at 6:32
  • Just to be clear, the test.py file is not going to change. I want to modify the python program that will execute test.py correctly supplying it the input and getting the output Commented Jul 19, 2018 at 6:33

1 Answer 1

1

You can add parameter stdout=PIPE to Popen, and use Popen.communicate to supply input and read the output instead.

from subprocess import Popen, PIPE
command = Popen(['python3', 'test.py'], stdin=PIPE, stdout=PIPE)
my_input = 'testpassword\n'
result, _ = command.communicate(my_input)

Please read Popen.communicate's documentation for more details: https://docs.python.org/3/library/subprocess.html#subprocess.Popen.communicate

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.