[英]Need to use a variable in an os.system command in python
I am new to python and I need to use a variable in the os.system
command, here's my code so far 我是python的新手,我需要在
os.system
命令中使用一个变量, os.system
,这是我的代码
import os , sys
s = raw_input('test>')
then i want to use the varable s
in an os.system
command so I was thinking something like os.system("shutdown -s -t 10 -c" 's')
然后我想用varable
s
在os.system
命令,所以我想这样os.system("shutdown -s -t 10 -c" 's')
I don't want answers for that specific command I just want to know in general but if you are going to use an example use shutdown 我不想要我通常只想知道的特定命令的答案,但是如果您要使用示例,请使用shutdown
then i want to use the varable s in an os.system
然后我想在os.system中使用varable
Use string.format
function. 使用
string.format
函数。
os.system("shutdown -s -t 10 -c {}".format(s))
You can use os.system
to execute the particular command, in which case you can join the two strings either by using the +
operator, string formatting ( .format()
), string substitution or some other method. 您可以使用
os.system
执行特定的命令,在这种情况下,可以使用+
运算符,字符串格式( .format()
),字符串替换或其他方法将两个字符串连接在一起。
However, consider the case when the user enters the command 5; rm -rf /
但是,请考虑用户输入命令
5; rm -rf /
5; rm -rf /
or some other malicious command. 5; rm -rf /
或其他一些恶意命令。 Instead of using os.system
you might want to take a look at subprocess 您可能不希望使用
os.system
而是看os.system
流程
If you use subprocess you might find the following example handy: 如果使用子流程,可能会发现以下示例很方便:
import subprocess
s = raw_input('test>')
subprocess.call(["shutdown", "-s", "-t", "10", "-c", s])
os.system
takes a string as the argument, so you can use anything that modifies a string. os.system
将字符串作为参数,因此您可以使用任何可修改字符串的东西。 For example, string formatting : 例如, 字符串格式 :
os.system('shutdown -s -t 10 -c {0}'.format(s))
Use subprocess.check_call , pass a list of args and you can add the variable wherever you like: 使用subprocess.check_call ,传递一个args列表,您可以在任意位置添加变量:
from subprocess import check_call
check_call(["shutdown", some_var ,"-s", "-t" "10", "-c"])
Passing place-holder "%s string alongside os.system" should work. 应该将占位符“%s字符串与os.system一起传递” 。
os.system() will execute the command in shell. os.system()将在shell中执行命令。
import os
var = raw_input('test>') # changed "s" variable to "var" to keep clean
os.system("shutdown -%s -t 10 -c", %(var)) # "var" will be passed to %s place holder
os.system("shutdown -s -t 10 -c" + s)
s
. s
周围没有引号。 That way you get the value the user entered and not just a literal "s".
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.