Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing arguments to shell script from Python

I'm writing a python program which passes arguments to a shell script.

Here's my python code:

import subprocess

Process=subprocess.Popen('./copyImage.sh %s' %s str(myPic.jpg))

And my "copyImage.sh":

#!/bin/sh

cp /home/pi/project/$1 /home/pi/project/newImage.jpg

I can run the script on terminal without problems. But when executing the python code, the terminal returned "NameError: name 'myPic' is not defined".

If I change the syntax to

Process=subprocess.Popen('./copyImage.sh %s' %s "myPic.jpg")

Then the terminal returned "OSError: [Errno 2] No such file or directory".

I've followed this: Python: executing shell script with arguments(variable), but argument is not read in shell script but it didn't help.

like image 859
RRWW Avatar asked Jul 21 '26 01:07

RRWW


2 Answers

The subprocess module is expecting a list of arguments, not a space-separated string. The way you tried caused python to look for a program called "copyImage.sh myPic.jpg" and call it with no arguments, whereas you wanted to look for a program called copyImage.sh and call it with one argument.

subprocess.check_call(['copyImage.sh', 'myPic.jpg'])

I also want to mention, since your script simply calls copy in a shell, you should probably cut out the middleman and just use python's shutil.copy directly. It's a more appropriate tool than running a subprocess for this task.

like image 132
wim Avatar answered Jul 22 '26 14:07

wim


Using os.system call is the way to go as:

  1. os.system does find your shell script in the environment
  2. you can append as many arguments as you need to the destination shell script

Example:

os.system('myshellscript1 ' + arg1 + ' ' + arg2)
like image 21
david m lee Avatar answered Jul 22 '26 13:07

david m lee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!