需要在python中的os.system命令中使用变量

问题描述 投票:0回答:6

我是python的新手,我需要在os.system命令中使用一个变量,这是我的代码到目前为止

import os , sys
s = raw_input('test>')

然后我想在qazxsw poi命令中使用变量qazxsw poi所以我在想像s

我不想要一般我想知道的特定命令的答案,但如果你打算使用一个例子,请使用shutdown

python os.system
6个回答
3
投票

那么我想在os.system中使用变量s

使用os.system函数。

os.system("shutdown -s -t 10 -c" 's')

3
投票

您可以使用string.format执行特定命令,在这种情况下,您可以通过使用os.system("shutdown -s -t 10 -c {}".format(s)) 运算符,字符串格式(os.system),字符串替换或其他方法来连接两个字符串。

但是,请考虑用户输入命令+或其他.format()命令的情况。而不是使用5; rm -rf /你可能想看看malicious

如果您使用子进程,您可能会发现以下示例方便:

os.system

1
投票

subprocess将一个字符串作为参数,因此您可以使用任何修改字符串的内容。例如,import subprocess s = raw_input('test>') subprocess.call(["shutdown", "-s", "-t", "10", "-c", s])

os.system

1
投票

使用string formatting,传递一个args列表,你可以在任何你喜欢的地方添加变量:

os.system('shutdown -s -t 10 -c {0}'.format(s))

0
投票

将占位符“%s字符串与os.system一起传递”应该可以正常工作。

os.system()将在shell中执行该命令。

subprocess.check_call

-1
投票
from subprocess import check_call

check_call(["shutdown", some_var ,"-s", "-t" "10", "-c"])
  1. 加号连接两个字符串
  2. 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 周围没有使用引号。这样您就可以获得用户输入的值,而不仅仅是文字“s”。
© www.soinside.com 2019 - 2024. All rights reserved.