简体   繁体   English

如何在os.system中使用python变量?

[英]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. 我在python中创建了一个小的控制台脚本,我想在其中放入cowsay命令,但是牛说变量的名称,字符串在哪里,而不是变量中的字符串。 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')

You could use format to construct the string 您可以使用format来构造字符串

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. 但我更喜欢前者,特别是如果字符串变得更复杂。

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 / 如果用户输入moo; rm -rf /怎么办? moo; rm -rf / ? moo; rm -rf / guess what will happen. 猜猜会发生什么。 Also, word="$(cat /etc/passwd)" and word="$aliases" or words with backticks will yield non-expected results. 此外, word="$(cat /etc/passwd)"word="$aliases"或带有反引号的单词将产生非预期的结果。

You should use the Subprocess module , which takes care of escaping shell args and constructing the call: 您应该使用Subprocess模块 ,它负责转义shell args并构建调用:

>>> 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. 使用.communicate()进行简单调用,如文档中所述或下面的示例中所述。 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 |
                ||     ||

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM