我正在使用子進程模塊在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