如何使用字符串格式运行命令?

时间:2012-04-12 16:55:12

标签: python command string-formatting

我正在使用子进程模块在python中运行命令。但问题是我还想在命令中包含一个字符串(用于文件名)。

我想做的一个例子:

  from subprocess import call

  command = "cd/DirectoryName"

  call = [(command)]

在这个具体示例中,我希望DirectoryName是由用户确定的变量。

我试图无济于事:

  Desktop=raw_input()
  cmd="'cd %s'(Desktop/)"
  call([cmd])

这是我尝试在python shell中运行这些命令时遇到的错误。

    Chicken='Chicken'
    command = 'say %s' % (Chicken)
    print command
    say Chicken
    call([command])

    Traceback (most recent call last):
    File "/Applications/WingIDE.app/Contents/MacOS/src/debug/tserver/_sandbox.py", line 1,     in <module>
    # Used internally for debug sandbox under external interpreter
    File "/Library/Frameworks/EPD64.framework/Versions/7.2/lib/python2.7/subprocess.py", line 493, in call
    return Popen(*popenargs, **kwargs).wait()
    File "/Library/Frameworks/EPD64.framework/Versions/7.2/lib/python2.7/subprocess.py", line 679, in __init__
    errread, errwrite)
    File "/Library/Frameworks/EPD64.framework/Versions/7.2/lib/python2.7/subprocess.py", line 1228, in _execute_child
    raise child_exception
    OSError: [Errno 2] No such file or directory

试过这个,它让shell崩溃了。

    Chicken="Chicken"
    print Chicken
    Chicken
    call[("say %s" % (Chicken)]

2 个答案:

答案 0 :(得分:1)

这不是字符串插值的工作原理。

cmd='cd %s' % (Desktop,)

答案 1 :(得分:0)

首先,

cmd="'cd %s'(Desktop/)" 

似乎不会“打印”%s。

也许

cmd="'cd %s/'%(Desktop)"

但是我仍然不知道是否会插入,因为它在字符串内部可以使用“call”函数和python命令 - 不会在命令行上调用它吗?

相关问题