When you use Subprocess to invoke another module component through the shell, you need to judge the returned code. It is difficult to trace where the exception occurred when the raise Exception is required to determine the result of execution failure, or if the call tree is too complex. Sys.exit (1) Although it can also achieve the purpose of judging the results of execution, but it is difficult to track the location of the occurrence of the anomaly.
1 a.py 2 '--- b.py3 '--LS
a.py
1 Importsys, subprocess2 3 defexec_cmd (cmd):4 """Run shell Command"""5p = subprocess. Popen (Cmd,stdin =subprocess. PIPE,6stdout =subprocess. PIPE,7stderr =subprocess. STDOUT,8Shell =True)9 TenLog_content =p.communicate () [0] One A returnP.returncode, Log_content - - defMain (): thecmd ="python b.py" -Cmd_code, Cmd_log =exec_cmd (cmd) - if notCmd_code = =0: - RaiseException (Cmd_log) + - if __name__=='__main__': +Main ()
b.py
1 Importsys, subprocess2 3 defexec_cmd (cmd):4 """Run shell Command"""5p = subprocess. Popen (Cmd,stdin =subprocess. PIPE,6stdout =subprocess. PIPE,7stderr =subprocess. STDOUT,8Shell =True)9 TenLog_content =p.communicate () [0] One A returnP.returncode, Log_content - - defMain (): thecmd ="""ls c.py""" -Cmd_code, Cmd_log =exec_cmd (cmd) - if notCmd_code = =0: - RaiseException (Cmd_log) + - if __name__=='__main__': +Main ()
Operation Result:
1 waterforestdeimac:pythoncrawler waterforest$ python a.py2 Traceback (most recent):3File"a.py", line 21,inch<module>4 Main ()5File"a.py", Line 18,inchMain6 RaiseException (Cmd_log)7 Exception:traceback (most recent):8File"b.py", line 21,inch<module>9 Main ()TenFile"b.py", Line 18,inchMain One RaiseException (Cmd_log) AException:ls:c.py:no such fileorDirectory - - theWaterforestdeimac:pythoncrawler waterforest$
Python subprocess Shell Programming specification