how to use os.system() in python for running an shell order

℡╲_俬逩灬. 提交于 2019-12-04 17:27:36

try this

import os
def f():
    cmd1 = "echo 'yes' | read "
    os.system(cmd1)
f()

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.)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!