Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple inputs using subprocess.run in Python 3.7+

Suppose I have a python script called input_test.py:

first_name = input()
print(name)

From another python script called main.py, I can run input_test.py as follows:

import subprocess
file = home_dir + "input_test.py"
result = subprocess.run([sys.executable, file], input="Dan", capture_output=True, text=True)

This works really well for my purposes. Sometimes, though, I may require multiple inputs. Suppose we have input_test2.py:

first_name = input()
last_name = input()
print(first_name, last_name)

How do I pass two inputs (or potentially more) using subprocess.run? If that's not possible, is there a way to do this within python? As an aside, I'm working in Windows 10 inclusively.

like image 415
Dan P. Avatar asked Dec 04 '25 17:12

Dan P.


1 Answers

How do I pass two inputs (or potentially more) using subprocess.run?

The input function stops reading when it receives a newline character...so you just need to separate your inputs with newlines:

>>> import subprocess
>>> subprocess.run(['python', 'names.py'], input='Joe\nBiden\n', capture_output=True, text=True)
CompletedProcess(args=['python', 'names.py'], returncode=0, stdout='Joe Biden\n', stderr='')
like image 102
larsks Avatar answered Dec 06 '25 07:12

larsks