3

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?

code_dredd
  • 5,915
  • 1
  • 25
  • 53
Ortal Turgeman
  • 143
  • 4
  • 14
  • Try to add full path to mainGui_functions.sh. – Cyrus Aug 28 '16 at 14:12
  • have you tried adding quotes around entryVal...something like this `"%d \"%s\""` – danidee Aug 28 '16 at 14:15
  • Perhaps this might help, coming from the bash script end of things https://stackoverflow.com/questions/1983048/passing-a-string-with-spaces-as-a-function-argument-in-bash – Totem Aug 28 '16 at 14:15
  • Also, consider using `str.format` instead of interpolating with the `%` character, for a more Pythonic style. – code_dredd Aug 28 '16 at 14:20
  • Starting a Bash instance so you can source a file and then immediately exit is just weird. Unless this is a simplified version of something which is more complex in reality, you simply want `Popen(['bash', 'mainGui_functions', str(commandNum.get()), entryVal])` (the `'bash'` can be omitted, too, if the script has execute permission and a proper shebang line). – tripleee Aug 28 '16 at 15:16

2 Answers2

4

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])
aruisdante
  • 8,875
  • 2
  • 30
  • 37
0

Put quotes around it in your bash command line – e.g.,

subprocess.Popen(['bash', '-c', '. mainGui_functions.sh %d "%s"' % (commandNum.get(), entryVal)])
Benjamin Barenblat
  • 1,311
  • 6
  • 19