2014-10-11 5 views
0

bash 명령 (cmd)을 인수로 사용하는 Python 함수를 만들고 나서 이 명령을 실행하려고합니다.bash 명령을 호출하는 Python 함수

하지만 몇 가지 문제가 있어요 것은 ...

내 프로그램입니다 :

그것은 "LS"또는 같은 명령을 작동
import subprocess 

def main(): 
    runCommand("ls") 
    runCommand("ls -l") 
    runCommand("cd /") 
    runCommand("ls -l") 

def runCommand(cmd): 
    subprocess.Popen(cmd) 

"사람"하지만 "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 

답변

1

당신은 당신의 명령 목록에서의 옵션을 넣어해야 작동

subprocess.Popen(['ls','-l']) 
+0

예,하지만 당신은 ([ 'CD를', '/']) 주는 이유를 알고 일어날 것 나에게 : "그런 파일이나 디렉토리가 없다"는 오류가 있습니까? – jean

+0

'subprocess.Popen ([ 'cd', '/'], shell = True)'를 사용해야합니다! 하지만 디렉토리를 바꾸려면 더 좋은 방법은'os.chdir'을 사용하는 것입니다. – Kasramvd

+0

subprocess.Popen ([ 'ls', '-l'])은 잘 작동합니다. shell = True는 필요 없습니다. – user1277476

관련 문제