如何在 python 中使用 os.system() 来运行 shell 命令
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18357655/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to use os.system() in python for running an shell order
提问by user2703588
In some shell script, you need to confirm "yes" to run the shell, well, an easier way is using "yes" and pipe, like this:
在某些 shell 脚本中,您需要确认“yes”才能运行 shell,嗯,更简单的方法是使用“yes”和管道,如下所示:
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.
然后,您可以自动运行 shell 脚本而不再回答“是”。今天,当我通过尝试在 python 中使用它时:os.system("yes|**.sh"),我得到了一个错误。
Here is my test.py file:
这是我的 test.py 文件:
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
并通过键入:python test.py 在 shell 中运行。故障信息是:是:标准输出:管道损坏是:写错误
but if i type "yes|read" in shell,it works well. may anyone tell me why?
但是如果我在 shell 中输入“yes|read”,它运行良好。谁能告诉我为什么?
回答by duck
try this
尝试这个
import os
def f():
cmd1 = "echo 'yes' | read "
os.system(cmd1)
f()
回答by tripleee
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.
在管道关闭后yes
继续尝试写入管道时,您在外壳中运行的子进程也会收到“管道已关闭”信号,但某些外壳已配置为捕获并忽略此错误,因此您看不到错误信息。无论哪种方式,它都是无害的。
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.
不过,目前还不清楚您希望这段代码能完成什么;read
在子进程中运行根本没有意义,因为执行该子进程read
会立即退出。
If you want to print yes
repeatedly, that's easy enough to do in Python itself.
如果您想yes
重复打印,在 Python 本身中很容易做到。
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.
如果您想测试自己的程序,您可以更改代码,以便在启用调试标志的情况下运行时不需要交互式输入。无论如何,如果这是您的目标,那么您目前的方法是由内而外的;父 (Python) 进程将在子进程管道运行时等待。
(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.)
(当你长大后,你会发现如何将输入作为命令行参数传递,这样你的脚本基本上就不需要交互式提示了。出于多种原因,这是一个更好的设计,但能够自动测试你的代码当然是其中之一。)