在os.system命令中附加变量时出错 - Python窗口

时间:2014-06-13 03:37:53

标签: python

嗨这个代码有问题

    currentdirectory = os.getcwd()
    processfile=currentdirectory+"\ClientProcessList.txt"
    print processfile
    os.system('WMIC /OUTPUT: %s PROCESS get Caption,Commandline,Processid') % processfile

错误:

os.system('WMIC /OUTPUT: %s PROCESS get Caption,Commandline,Processid') % pr ocessfile TypeError: unsupported operand type(s) for %: 'int' and 'str'

我甚至试过这个:

os.system('WMIC /OUTPUT: '+processfile+' PROCESS get Caption,Commandline,Processid')

错误:

Invalid Global Switch.

1 个答案:

答案 0 :(得分:0)

格式化字符串的语法是:

"some string %s" % "the string"

但在()

之前有括号%
some_function("some string %s") % "the string"   # this will try to apply 
                                                 # the % operator to the value
                                                 # returned by the function.   

由于您要将格式应用于作为参数传递的字符串,因此应该是:

some_function("some string %s " % "the string")

在你的情况下:

os.system('WMIC /OUTPUT: %s PROCESS get Caption,Commandline,Processid' % processfile)