Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/365.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
需要在python中的os.system命令中使用变量_Python_Os.system - Fatal编程技术网

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

需要在python中的os.system命令中使用变量,python,os.system,Python,Os.system,我是python新手,我需要在os.system命令中使用一个变量,这是我到目前为止的代码 import os , sys s = raw_input('test>') 然后我想在一个os.system命令中使用varables,所以我想到了类似于os.system(“shutdown-s-t10-c”'s') 我不想知道具体命令的答案,我只是想知道一般情况,但如果您要使用示例,请使用shutdown os.system("shutdown -s -t 10 -c" + s) 加号连接

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

import os , sys
s = raw_input('test>')
然后我想在一个
os.system
命令中使用varable
s
,所以我想到了类似于
os.system(“shutdown-s-t10-c”'s')

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

os.system("shutdown -s -t 10 -c" + s)
  • 加号连接两个字符串
  • s
    周围不使用引号。通过这种方式,您可以获得用户输入的值,而不仅仅是文字“s”
  • 然后我想在操作系统中使用变量

    使用函数

    os.system("shutdown -s -t 10 -c {}".format(s))
    
    将字符串作为参数,因此可以使用任何修改字符串的内容。例如:


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

    但是,考虑用户输入命令<代码> 5的情况;rm-rf/或其他一些命令。您可能不想使用

    os.system
    ,而是想看看

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

    import subprocess
    s = raw_input('test>')
    subprocess.call(["shutdown", "-s", "-t", "10", "-c", s])
    
    使用,传递参数列表,您可以在任意位置添加变量:

    from subprocess import check_call
    
    check_call(["shutdown", some_var ,"-s", "-t" "10", "-c"])
    

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

    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
    
    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