How to use python variable in os.system? [duplicate]

lazy solution is to simply concatenate the word:

>>> import os
>>> word="moo"
>>> os.system('cowsay ' + word)
 _____ 
< moo >
 ----- 
        \   ^__^
         \  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||
0

BUT you should not do this.
What if the user inputs moo; rm -rf /? guess what will happen.
Also, word="$(cat /etc/passwd)" and word="$aliases" or words with backticks will yield non-expected results.

You should use the Subprocess module, which takes care of escaping shell args and constructing the call:

>>> import subprocess
>>> subprocess.Popen(['cowsay', word])
<subprocess.Popen object at 0x7fe8c7656c18>
>>>  _____ 
< moo >
 ----- 
        \   ^__^
         \  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||

Use .communicate() for simple invocations, as described in the docs or as in the example below.
And now you don’t have to worry about injections:

>>> word="$(cat /etc/passwd)"
>>> stdout, stderr = subprocess.Popen(
                     ['cowsay', word]).communicate()
 ____________________ 
< $(cat /etc/passwd) >
 -------------------- 
        \   ^__^
         \  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||

Leave a Comment