Reputation: 477
I have a Python script that calls another shell script -
arg1 = "-a"
arg2 = "-b"
arg3 = "Some String"
argList = ["script.sh", arg1, arg2, arg3]
subprocess.call(argList)
When I run the script, arg3
gets split to "Some"
and "String"
and is passed as two separate arguments.
How can I overcome this to pass "Some String"
as a single argument?
EDIT: SOLVED
I was calling another function internally in the called script by passing the arguments as $1, $2, $3, .. etc. When I should've quoted the arguments that might have whitespaces like $1, $2, "$3" .. etc. Sorry for the confusion.
Upvotes: 5
Views: 529
Reputation: 6335
This is more an extended comment than an answer.
Your code works fine in my Debian 9.3
$ cat sc.sh
#!/bin/sh
# Above line is mandatory - otherwise python returns error of unkonwn format
echo "arg1=$1"
echo "arg2=$2"
echo "arg3=$3"
echo "arg4=$4"
$ chmod +x sc.sh
$ pwd
/home/gv
$ cat test.py
import subprocess
arg1 = "-a"
arg2 = "-b"
arg3 = "some string"
arglist = ["/home/gv/sc.sh", arg1, arg2, arg3]
subprocess.call(arglist)
$ python test.py
arg1=-a
arg2=-b
arg3=some string
arg4=
PS : In my system python 2.17.14 is installed and bash 4.4.12
Upvotes: 0
Reputation: 784948
This should work:
import subprocess
arg1 = "-a"
arg2 = "-b"
arg3 = "Some String"
argList = ["sh", "script.sh", arg1, arg2, arg3]
subprocess.call(argList)
and inside script.sh
printf '%s\n' "$@"
Make sure "$@"
is quoted to avoid word splitting inside your shell script.
This will output:
-a
-b
Some String
Upvotes: 1
Reputation: 5261
Try this:
import shlex, subprocess
args=shlex.split('script.sh -a -b "Some String"')
subprocess.Popen(args)
Upvotes: 0