问题
I am new to python and I need to use a variable in the os.system
command, here's my code so far
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')
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
回答1:
then i want to use the varable s in an os.system
Use string.format function.
os.system("shutdown -s -t 10 -c {}".format(s))
回答2:
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.
However, consider the case when the user enters the command 5; rm -rf /
or some other malicious command. Instead of using os.system
you might want to take a look at subprocess
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])
回答3:
os.system takes a string as the argument, so you can use anything that modifies a string. For example, string formatting:
os.system('shutdown -s -t 10 -c {0}'.format(s))
回答4:
Use subprocess.check_call, pass a list of args and you can add the variable wherever you like:
from subprocess import check_call
check_call(["shutdown", some_var ,"-s", "-t" "10", "-c"])
回答5:
Passing place-holder "%s string alongside os.system" should work.
os.system() will execute the command in 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
回答6:
os.system("shutdown -s -t 10 -c" + s)
- The plus sign joins two strings
- No quotes are used around
s
. That way you get the value the user entered and not just a literal "s".
来源:https://stackoverflow.com/questions/32047137/need-to-use-a-variable-in-an-os-system-command-in-python