我试图在bash脚本中运行Python和bash命令.在bash脚本中,我想执行Python循环包含的一些bash命令:
#!/bin/bash
python << END
for i in range(1000):
#execute? some bash command such as echoing i
END
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?
dom*_*om0 39
使用子进程,例如:
import subprocess
# ...
subprocess.call(["echo", i])
Run Code Online (Sandbox Code Playgroud)
还有另一个功能subprocess.call:subprocess.check_call.它与调用完全相同,只是如果执行的命令以非零退出代码返回,则抛出异常.这通常是脚本和实用程序中的可行行为.
subprocess.check_output行为相同check_call,但返回程序的标准输出.
如果您不需要shell功能(例如变量扩展,通配符等),请不要使用shell = True(默认情况下为shell = False).如果你使用shell = True,那么shell转义就是你使用这些函数的工作,如果传递了未经验证的用户输入,它们就是一个安全漏洞.
os.system()也是如此 - 它是安全问题的常见来源.不要使用它.
小智 17
查看子进程模块.有Popen方法和一些包装函数call.
如果需要检查输出(检索结果字符串):
output = subprocess.check_output(args ....)
Run Code Online (Sandbox Code Playgroud)如果要在继续之前等待执行结束:
exitcode = subprocess.call(args ....)
Run Code Online (Sandbox Code Playgroud)如果您需要更多功能,如设置环境变量,请使用基础Popen构造函数:
subprocess.Popen(args ...)
Run Code Online (Sandbox Code Playgroud)记住子进程是更高级别的模块.它应该替换OS模块中的旧功能.
| 归档时间: |
|
| 查看次数: |
90256 次 |
| 最近记录: |