如何python脚本中运行bash命令? [英] How to run bash command inside python script?

查看:1361
本文介绍了如何python脚本中运行bash命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在bash脚本我试图运行Python和bash命令两者。
在一些地方我想一个Python循环中执行一些bash命令。

In a bash script I am trying to run python and bash command both. In some where I want to execute some bash command inside a python loop.

#!/bin/bash

python << END
for i in range(1000):
    #execute‬ some bash command such as echoing i
END

我怎么能这样做呢?

how can I do this?

推荐答案

最简单的方法,我们不推荐的:

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.

这篇关于如何python脚本中运行bash命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆