我正在尝试创建一个将bash命令(cmd)作为参数的Python函数,然后 执行该命令。
但我有一些问题......
这是我的计划:
import subprocess
def main():
runCommand("ls")
runCommand("ls -l")
runCommand("cd /")
runCommand("ls -l")
def runCommand(cmd):
subprocess.Popen(cmd)
它适用于“ls”或“who”之类的命令,但当它变得更长时,例如“ls -l”或“cd /”,它会给我一个错误。
Traceback (most recent call last):
File "<string>", line 1, in ?
File "test.py", line 8, in main
runCommand("ls -l")
File "test.py", line 14, in runCommand
subprocess.Popen(cmd)
File "/usr/lib64/python2.4/subprocess.py", line 550, in __init__
errread, errwrite)
File "/usr/lib64/python2.4/subprocess.py", line 996, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
答案 0 :(得分:1)
您需要将命令及其选项放在列表中:
subprocess.Popen(['ls','-l'])