How to call a shell script from python code?

2019-01-04 05:48发布

How to call a shell script from python code?

标签: python shell
10条回答
Anthone
2楼-- · 2019-01-04 06:26

Use the subprocess module as mentioned above.

I use it like this:

subprocess.call(["notepad"])
查看更多
地球回转人心会变
3楼-- · 2019-01-04 06:26

Subprocess is good but some people may like scriptine better. Scriptine has more high-level set of methods like shell.call(args), path.rename(new_name) and path.move(src,dst). Scriptine is based on subprocess and others.

Two drawbacks of scriptine:

  • Current documentation level would be more comprehensive even though it is sufficient.
  • Unlike subprocess, scriptine package is currently not installed by default.
查看更多
放荡不羁爱自由
4楼-- · 2019-01-04 06:29
import os
import sys

Assuming test.sh is the shell script that you would want to execute

os.system("sh test.sh")
查看更多
Bombasti
5楼-- · 2019-01-04 06:32

The subprocess module will help you out.

Blatantly trivial example:

>>> import subprocess
>>> subprocess.call(['./test.sh']) # Thanks @Jim Dennis for suggesting the []
0 
>>> 

Where test.sh is a simple shell script and 0 is its return value for this run.

查看更多
一纸荒年 Trace。
6楼-- · 2019-01-04 06:33

Please Try the following codes :

Import Execute 

Execute("zbx_control.sh")
查看更多
欢心
7楼-- · 2019-01-04 06:35

In case the script is having multiple arguments

#!/usr/bin/python

import subprocess
output = subprocess.call(["./test.sh","xyz","1234"])
print output

Output will give the status code. If script runs successfully it will give 0 otherwise non-zero integer.

podname=xyz  serial=1234
0

Below is the test.sh shell script.

#!/bin/bash

podname=$1
serial=$2
echo "podname=$podname  serial=$serial"
查看更多
登录 后发表回答