Python: run shell script with manual input

2019-02-28 04:34发布

For example, the shell script takes an integer at a prompt and returns it.

Enter an integer:
--> 3
3

I'm using subprocess.check_call(["./myScript"]) to run the shell script. How can I automate sending the "3" in as in the example above? So far all my searching has only recovered how to run a script with command line arguments, not this kind of manual input.

标签: python shell
2条回答
走好不送
2楼-- · 2019-02-28 05:02

You probably want to use the subprocess.Popen.communicate() function. The docs are quite expressive.

查看更多
孤傲高冷的网名
3楼-- · 2019-02-28 05:15

As the earlier answer explained subprocess.Popen can be used to create process that can be interacted with communicate. communicate takes string as a parameter that will be passed to the created process and returns tuple (stdout, stderr). Below is a short example of two Python scripts communicating with it:

Child

nums = raw_input()
print sum((int(n) for n in nums.split()))

Parent

import subprocess

p = subprocess.Popen(['python', 'test.py'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
out, err = p.communicate('3 4 5')
print 'From other process: ' + out

Output

From other process: 12
查看更多
登录 后发表回答