如何在 Python 脚本中运行 bash 命令
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26236126/
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 run bash commands inside of a Python script
提问by Md. Zakir Hossan
I am trying to run both Python and bash commands in a bash script. In the bash script, I want to execute some bash commands enclosed by a Python loop:
我正在尝试在 bash 脚本中同时运行 Python 和 bash 命令。在 bash 脚本中,我想执行一些包含在 Python 循环中的 bash 命令:
#!/bin/bash
python << END
for i in range(1000):
#execute? some bash command such as echoing i
END
How can I do this?
我怎样才能做到这一点?
回答by dom0
Use subprocess, e.g.:
使用subprocess,例如:
import subprocess
# ...
subprocess.call(["echo", i])
There is another function like subprocess.call: subprocess.check_call. It is exactly like call, just that it throws an exception if the command executed returned with a non-zero exit code. This is often feasible behaviour in scripts and utilities.
还有另一个功能,如subprocess.call:subprocess.check_call。它与 call 完全一样,只是如果执行的命令返回一个非零退出代码,它会抛出异常。这在脚本和实用程序中通常是可行的行为。
subprocess.check_outputbehaves the same as check_call, but returns the standard output of the program.
subprocess.check_output行为与 相同check_call,但返回程序的标准输出。
If you do not need shell features (such as variable expansion, wildcards, ...), never use shell=True(shell=False is the default). Ifyou use shell=True then shell escaping is your job with these functions and they're a security hole if passed unvalidated user input.
如果您不需要 shell 功能(例如变量扩展、通配符等),请不要使用 shell=True(shell=False 是默认值)。如果您使用 shell=True 那么 shell 转义是您使用这些函数的工作,如果通过未经验证的用户输入,它们就是一个安全漏洞。
The same is true of os.system() -- it is a frequent source of security issues. Don't use it.
os.system() 也是如此——它是安全问题的常见来源。不要使用它。
回答by dom0
Look in to the subprocessmodule. There is the Popen method and some wrapper functions like call.
查看子流程模块。有 Popen 方法和一些包装函数,如call.
If you need to check the output (retrieve the result string):
output = subprocess.check_output(args ....)If you want to wait for execution to end before proceeding:
exitcode = subprocess.call(args ....)If you need more functionality like setting environment variables, use the underlying Popen constructor:
subprocess.Popen(args ...)
如果您需要检查输出(检索结果字符串):
output = subprocess.check_output(args ....)如果您想在继续之前等待执行结束:
exitcode = subprocess.call(args ....)如果您需要更多功能,例如设置环境变量,请使用底层 Popen 构造函数:
subprocess.Popen(args ...)
Remember subprocess is the higher level module. It should replace legacy functions from OS module.
记住子流程是更高级别的模块。它应该替换 OS 模块中的旧功能。
回答by Ger Mc
I used this when running from my IDE (PyCharm).
我在从我的 IDE (PyCharm) 运行时使用了它。
import subprocess
subprocess.check_call('mybashcommand', shell=True)

