如何在Python脚本中运行bash命令 [英] How to run bash commands inside of a Python script

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

问题描述

我正在尝试在bash脚本中同时运行Python和bash命令. 在bash脚本中,我想执行Python循环中包含的一些bash命令:

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:

#!/bin/bash

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

我该怎么做?

推荐答案

使用子流程,例如:

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.

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

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