更新时间:2023-01-15 22:48:16
使用子流程,例如:
import subprocess
# ...
subprocess.call(["echo", i])
还有另一个功能,例如subprocess.call
:subprocess.check_call
.这与调用完全一样,只是如果执行的命令返回的返回值非零,则它将引发异常.在脚本和实用程序中,这通常是可行的行为.
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.check_output
的行为与check_call
相同,但返回程序的标准输出.
subprocess.check_output
behaves the same as check_call
, but returns the standard output of the program.
如果不需要shell功能(例如变量扩展,通配符等),请不要使用shell = True (默认情况下为shell = False). 如果使用shell = True,则使用这些功能进行外壳转义是您的工作,并且如果传递未经验证的用户输入,则它们是一个安全漏洞.
If you do not need shell features (such as variable expansion, wildcards, ...), never use shell=True (shell=False is the default). If you use shell=True then shell escaping is your job with these functions and they're a security hole if passed unvalidated user input.
os.system()也是如此-它是安全问题的常见来源.不要使用它.
The same is true of os.system() -- it is a frequent source of security issues. Don't use it.