How do I use a python variable in os.system?

I am creating a small console script in python and I would like to add the cowsay command to it, but the cow says the name of the variable where the string is, not the string inside the variable. How can I get the cow to say a string inside a variable?

if (command == 'cow'):
    word = raw_input('What does the cow say?  ')
    os.system('cowsay word')

      

+3


source to share


2 answers


the lazy solution is to simply concatenate the word:

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

      

BUT you shouldn't do this. What if the user enters moo; rm -rf /

? guess what will happen. Moreover, word="$(cat /etc/passwd)"

and word="$aliases"

or words with opposite conclusions will lead to unexpected results.

You should use the Subprocess Module , which takes care of escaping shell arguments and building the call:



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

      

Use .communicate()

for simple calls 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 |
                ||     ||

      

+4


source


You can use format

to build a string

os.system('cowsay {}'.format(word))

      

Or simple string concatenation



os.system('cowsay ' + word)

      

But I prefer the former, especially if the string gets more complex.

+3


source







All Articles