Skip to content Skip to sidebar Skip to footer

Python: Executing Shell Script With Arguments(variable), But Argument Is Not Read In Shell Script

I am trying to execute a shell script(not command) from python: main.py ------- from subprocess import Popen Process=Popen(['./childdir/execute.sh',str(var1),str(var2)],shell=True

Solution 1:

The problem is with shell=True. Either remove that argument, or pass all arguments as a string, as follows:

Process=Popen('./childdir/execute.sh %s %s' % (str(var1),str(var2),), shell=True)

The shell will only pass the arguments you provide in the 1st argument of Popen to the process, as it does the interpretation of arguments itself. See a similar question answered here. What actually happens is your shell script gets no arguments, so $1 and $2 are empty.

Popen will inherit stdout and stderr from the python script, so usually there's no need to provide the stdin= and stderr= arguments to Popen (unless you run the script with output redirection, such as >). You should do this only if you need to read the output inside the python script, and manipulate it somehow.

If all you need is to get the output (and don't mind running synchronously), I'd recommend trying check_output, as it is easier to get output than Popen:

output = subprocess.check_output(['./childdir/execute.sh',str(var1),str(var2)])
print(output)

Notice that check_output and check_call have the same rules for the shell= argument as Popen.


Solution 2:

you actually are sending the arguments ... if your shell script wrote a file instead of printing you would see it. you need to communicate to see your printed output from the script ...

from subprocess import Popen,PIPE

Process=Popen(['./childdir/execute.sh',str(var1),str(var2)],shell=True,stdin=PIPE,stderr=PIPE)
print Process.communicate() #now you should see your output

Solution 3:

If you want to send arguments to shellscript from python script in a simple way.. You can use python os module :

import os  
os.system(' /path/shellscriptfile.sh {} {}' .format(str(var1), str(var2)) 

If you have more arguments.. Increase the flower braces and add the args.. In shellscript file.. This will read the arguments and u can execute the commands accordingly


Post a Comment for "Python: Executing Shell Script With Arguments(variable), But Argument Is Not Read In Shell Script"