问题
In some shell script, you need to confirm "yes" to run the shell, well, an easier way is using "yes" and pipe, like this:
yes | test.py
then, you can run the shell script automatically without answer "yes" anymore. today, when i use this in python by trying : os.system("yes|**.sh"), i got an fault.
Here is my test.py file:
import os
def f():
cmd1 = "yes | read "
os.system(cmd1)
f()
and run in shell by typing : python test.py. the fault information is : yes: standard output: Broken pipe yes: write error
but if i type "yes|read" in shell,it works well. may anyone tell me why?
回答1:
try this
import os
def f():
cmd1 = "echo 'yes' | read "
os.system(cmd1)
f()
回答2:
The subprocess you run in the shell also gets the "pipe closed" signal when yes
continues to try to write to the pipe after the pipeline is closed, but some shells are configured to trap and ignore this error, so you don't see an error message. Either way, it's harmless.
It's unclear what you hope this code will accomplish, though; running read
in a subprocess makes no sense at all, as the subprocess which performs the read
will immediately exit.
If you want to print yes
repeatedly, that's easy enough to do in Python itself.
while True:
print('yes')
If you want to test your own program, you could change the code so it doesn't require interactive input when running with a debugging flag enabled. Your current approach is inside out if that's your goal, anyway; the parent (Python) process will wait while the subprocess pipeline runs.
(When you grow up, you will discover how to pass input as command-line arguments, so that your scripts will basically never require interactive prompting. This is a better design for a number of reasons, but being able to automate testing of your code is certainly one of them.)
来源:https://stackoverflow.com/questions/18357655/how-to-use-os-system-in-python-for-running-an-shell-order