Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass parameters with whitespaces to bash through subprocess?

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.

like image 226
entropy.maximum Avatar asked Nov 08 '22 11:11

entropy.maximum


1 Answers

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
like image 135
anubhava Avatar answered Nov 14 '22 04:11

anubhava