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

2024-03-29 04:39:28 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

然后我想在os.system命令中使用varables,所以我在想类似os.system("shutdown -s -t 10 -c" 's')的东西

我不想知道这个特定命令的答案,我只想知道一般情况,但是如果您要使用一个示例,请使用shutdown


Tags: 答案代码testimport命令示例inputraw
3条回答

^{}接受字符串作为参数,因此可以使用任何修改字符串的内容。例如,string formatting

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

可以使用os.system执行特定命令,在这种情况下,可以使用+运算符、字符串格式(.format())、字符串替换或其他方法连接这两个字符串。

但是,考虑用户输入命令5; rm -rf /或其他malicious命令的情况。与其使用os.system,不如查看subprocess

如果使用subprocess,您可能会发现下面的示例很方便:

import subprocess
s = raw_input('test>')
subprocess.call(["shutdown", "-s", "-t", "10", "-c", s])

then i want to use the varable s in an os.system

使用^{}函数。

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

相关问题 更多 >