我正在使用子进程模块在python中运行命令。但问题是我也想在命令中包含一个字符串(用于文件名)。如何以字符串格式运行命令?
什么,我想要做的一个例子:
from subprocess import call
command = "cd/DirectoryName"
call = [(command)]
在这个具体的例子我想目录名是由用户决定的变量。
我试图无济于事:
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
刚试过这个,它使得壳体崩溃。
Chicken="Chicken"
print Chicken
Chicken
call[("say %s" % (Chicken)]
感谢您对语法的帮助。我更新了这个问题,虽然我得到的错误。我没有看到文件或目录如何影响我想执行的命令。 – ironcyclone 2012-04-12 17:23:10
简单。没有命令名称为“cd”。有一个“cd”命令,但这不是你正在执行的。 – 2012-04-12 17:25:02
但在我发布的例子中,说让电脑说出这个词。就像我在执行通话声明时应该说'鸡'一样。 – ironcyclone 2012-04-12 17:46:03