How to use python variable in os.system?

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

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

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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 |
                ||     ||

Method 2

You could use format to construct the string

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

Or simple string concatenation

os.system('cowsay ' + word)

But I prefer the former, especially if the string get more complicated.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x