简体   繁体   中英

How to send a string with spaces from Python to Bash sub-process as a single value?

I'm trying to send a variable from a python script to a bash script. I'm using popen like as shown below:

subprocess.Popen(["bash", "-c", ". mainGui_functions.sh %d %s" % (commandNum.get(), entryVal)])

However, entryVal can sometimes contain one or more white space characters. In that case I divide the string into multiple arguments ($2,$3..)

How can i get it in one argument?

Simple solution #1: You do it the exact same way you'd do it if you were typing the input on the commandline; put it in quotes:

subprocess.Popen(["bash", "-c", ". mainGui_functions.sh {} '{}'".format(commandNum.get(), entryVal)])

Simple solution #2: If mainGui_functions.sh is already executable, then you can just omit the bash part and pas args to it directly. In this case, subprocess takes care of making sure an entry with whitespace winds up as a single arg for you:

subprocess.Popen(["mainGui_functions.sh", str(commandNum.get()), entryVal])

在bash命令行中添加引号 - 例如,

subprocess.Popen(['bash', '-c', '. mainGui_functions.sh %d "%s"' % (commandNum.get(), entryVal)])

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