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)

Better use subprocess, e.g.:

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.

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.

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)