Python subprocess Shell Programming specification

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.