更新时间:2023-01-15 22:36:15
最简单的方法,我们不推荐的:
The simplest way, not recommendable:
import os
# ...
os.system(commandString)
更好地利用子,例如:
import subprocess
# ...
subprocess.call(["echo", i], shell=True)
请注意,壳牌逃逸是这些功能的工作,他们如果获得通过未经验证的用户输入的一个安全漏洞。
Note that shell escaping is your job with these functions and they're a security hole if passed unvalidated user input.
如果您不需要外壳的功能(如变量扩展,通配符,...),从未使用shell =真。然后,你不需要做自己逃跑等。
If you do not need shell features (such as variable expansion, wildcards, ...), never use shell=True. Then you don't need to do escaping yourself etc.
有像 subprocess.call
另一个功能: subprocess.check_call
。它酷似电话,只是它抛出一个异常,如果执行的命令用非零退出code返回。这通常是在脚本和实用程序可行的行为。
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.