简体   繁体   中英

How to execute a shell script through python

I have a script say abc.sh which has list of commands with flags. example

//abc.sh
echo $FLAG_name
cp   $FLAG_file1   $FLAG_file2
echo 'file copied'

I want to execute this script through python code. say

//xyz.py

name = 'FUnCOder'
filename1  = 'aaa.txt'
filename2 = 'bbb.txt'

subprocess.call([abc.sh, name, filename1, filname2], stdout=PIPE, stderr=PIPE, shell=True)

This call is not working.

What are the other options?

Also the shell script file is in some other directory. And I want the output to go in logs.

Usually you want to use Popen since you have process control afterwards. Try:

process = subprocess.Popen(['abc.sh', name, filename1, filname2], stdout=PIPE, stderr=PIPE)
process.wait() # Wait for process to complete.

# iterate on the stdout line by line
for line in process.stdout.readlines():
    print(line)

Try this:

//xyz.py

name = 'FUnCOder'
filename1  = 'aaa.txt'
filename2 = 'bbb.txt'

process = subprocess.Popen(['abc.sh', name, filename1, filname2], stdout=PIPE)
process.wait()

Notice that 'abc.sh' is in quotes because it's not a variable name, but the command you're calling.

I would also, in general, recommend using shell=False , though in some cases it is necessary to use shell=True .

To put output into a file try:

with open("logfile.log") as file:
    file.writelines(process.stdout)

I know this is a old question, below is the way if you are using Python 3.5 & above versions.

import subprocess
process = subprocess.run('script.sh', shell=True, check=True, timeout=10) 

Ref: https://docs.python.org/3.5/library/subprocess.html#subprocess.run

我在 macOS 上运行我使用的 shell 脚本:

process = subprocess.Popen([abc.sh, name, filename1, filname2], shell=True)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM