2012-09-14 4 views
0

에 나는 첫 번째 명령이 성공하는 경우에만 나는이쉘의 && 및 || 쉘에서 파이썬

cmd1 && cmd2 

을 할 것입니다 두 번째 명령을 실행하고 싶은 경우에 나는 처음 내가이

을 할 것이다 실패 할 경우 두 번째 명령을 실행해야하는 경우
cmd1 || cmd2 

파이썬 스크립트에서 subprocess.call을 통해 명령 목록을 호출합니다. 위의 작업을 수행하려면 어떻게해야합니까?

답변

5

shell=True에서 subprocess.call을 전달하면 임의의 쉘 명령을 실행할 수 있습니다. 그냥 escape/quote everything correctly인지 확인하십시오.

subprocess.call("true && echo yes!", shell=True) 

인쇄 yes! 반면,

subprocess.call("false && echo yes!", shell=True) 

인쇄 아무것도.

(당신은 탈출 또는 인용 && 또는 || 필요는 없지만, 그들에 공백이있는 파일 이름은 통증이있을 수 있습니다.)

가 이런 종류의
1

뭔가가 확장

In [227]: subprocess.Popen(['dir', '||', 'ls'], shell=True) 
Out[227]: <subprocess.Popen at 0x1e4dfb0> 

Volume in drive D has no label. 
Volume Serial Number is 4D5A-03B6 

Directory of D:\Dummy 

09/14/2012 03:54 PM <DIR>   . 
09/14/2012 03:54 PM <DIR>   .. 
       0 File(s)    0 bytes 
       2 Dir(s) 141,482,524,672 bytes free 

In [228]: subprocess.Popen(['dir', '&&', 'ls'], shell=True) 
Out[228]: <subprocess.Popen at 0x1e4df10> 
Volume in drive D has no label. 
Volume Serial Number is 4D5A-03B6 

Directory of D:\Dummy 

09/14/2012 03:54 PM <DIR>   . 
09/14/2012 03:54 PM <DIR>   .. 
       0 File(s)    0 bytes 
       2 Dir(s) 141,482,524,672 bytes free 
'ls' is not recognized as an internal or external command, 
operable program or batch file. 
1

작동합니다 @ larsmans 대답 - subprocess.call을 사용하고 어떤 이유로 든 shell=True을 설정하고 싶지 않은 경우 returncode 속성을 확인할 수 있습니다.
리턴 코드가 0이면 명령이 성공했습니다. CalledProcessError을 발생 시키려면 subprocess.check_call을 구현할 수도 있습니다. 유용한 정보가 있습니다. documentation

관련 문제