Skip to content Skip to sidebar Skip to footer

Python 2.7 - Quotes Added To Command When Using Popen To Execute From Variable

I'm trying to send a command through a socket from client to server to execute a command on the server and send the output back to me. Everything works fine if the command is one w

Solution 1:

Try make data an array of arguments (the first being the actual command).

For example:

commout = subprocess.Popen(['netstat', '-an'], stdout=subprocess.PIPE, shell=True)

The first element is a string representing the actual command (netstat), the next element is a string representing the first argument (-an).

To clarify, Popen(['echo', 'a', 'b'] is equivalent to echo a b on the command line, whereas Popen(['echo', 'a b'] would be equivalent to echo "a b" instead (ie. a single argument with a space between a and b.


Solution 2:

If you pass a list, each item in it will be quoted separately. In this case, just pass a string:

subprocess.Popen(data, stdout=subprocess.PIPE, shell=True)

Post a Comment for "Python 2.7 - Quotes Added To Command When Using Popen To Execute From Variable"