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条回答
太酷不给撩
2楼-- · 2019-01-04 06:36

There are some ways using os.popen() (deprecated) or the whole subprocess module, but this approach

import sys, os

os.system(command)

is one of the easiest.

查看更多
欢心
3楼-- · 2019-01-04 06:38

I'm running python 3.5 and subprocess.call(['./test.sh']) doesn't work for me.

I give you three solutions depends on what you wanna do with the output.

1 - call script. You will see output in your terminal. output is a number.

import subprocess 
output = subprocess.call(['test.sh'])

2 - call and dump execution and error into string. You don't see execution in your terminal unless you print(stdout). Shell=True as argument in Popen doesn't work for me.

import subprocess
from subprocess import Popen, PIPE

session = subprocess.Popen(['test.sh'], stdout=PIPE, stderr=PIPE)
stdout, stderr = session.communicate()

if stderr:
    raise Exception("Error "+str(stderr))

3 - call script and dump the echo commands of temp.txt in temp_file

import subprocess
temp_file = open("temp.txt",'w')
subprocess.call([executable], stdout=temp_file)
with open("temp.txt",'r') as file:
    output = file.read()
print(output)

Don't forget to take a look at the doc subprocess

查看更多
看我几分像从前
4楼-- · 2019-01-04 06:39

In case you want to pass some parameters to your shell script, you can use the method shlex.split():

import subprocess
import shlex
subprocess.call(shlex.split('./test.sh param1 param2'))

with test.sh in the same folder:

#!/bin/sh
echo $1
echo $2
exit 0

Outputs:

$ python test.py 
param1
param2
查看更多
迷人小祖宗
5楼-- · 2019-01-04 06:47

Subprocess module is a good module to launch subprocesses. You can use it to call shell commands as this:

subprocess.call(["ls","-l"]);
#basic syntax
#subprocess.call(args, *)

You can see its documentation here.

If you have your script written in some .sh file or a long string, then you can use os.system module. It is fairly simple and easy to call:

import os
os.system("your command here")
# or
os.system('sh file.sh')

This command will run the script once, to completion, and block until it exits.

查看更多
登录 后发表回答