Python subprocess shell 编程规范
使用subprocess通过shell调用另一个模块组件时,需要对返回的code进行判断。判断结果为执行失败时需要raise Exception,不然调用树过于复杂时,我们很难跟踪到异常发生的位置。sys.exit(1)虽然也可以达到对执行结果进行判断的目的,但是它难于追踪异常发生的位置。
1 a.py 2 `-- b.py 3 `-- ls
a.py
1 import sys, subprocess 2 3 def exec_cmd(cmd): 4 """Run shell command""" 5 p = subprocess.Popen(cmd,stdin = subprocess.PIPE, \ 6 stdout = subprocess.PIPE, 7 stderr = subprocess.STDOUT, 8 shell = True) 9 10 log_content = p.communicate()[0] 11 12 return p.returncode, log_content 13 14 def main(): 15 cmd = "python b.py" 16 cmd_code, cmd_log = exec_cmd(cmd) 17 if not cmd_code == 0: 18 raise Exception(cmd_log) 19 20 if __name__ == '__main__': 21 main()
b.py
1 import sys, subprocess 2 3 def exec_cmd(cmd): 4 """Run shell command""" 5 p = subprocess.Popen(cmd,stdin = subprocess.PIPE, \ 6 stdout = subprocess.PIPE, 7 stderr = subprocess.STDOUT, 8 shell = True) 9 10 log_content = p.communicate()[0] 11 12 return p.returncode, log_content 13 14 def main(): 15 cmd = """ls c.py""" 16 cmd_code, cmd_log = exec_cmd(cmd) 17 if not cmd_code == 0: 18 raise Exception(cmd_log) 19 20 if __name__ == '__main__': 21 main()
运行结果:
1 waterforestdeiMac:pythonCrawler waterforest$ python a.py 2 Traceback (most recent call last): 3 File "a.py", line 21, in <module> 4 main() 5 File "a.py", line 18, in main 6 raise Exception(cmd_log) 7 Exception: Traceback (most recent call last): 8 File "b.py", line 21, in <module> 9 main() 10 File "b.py", line 18, in main 11 raise Exception(cmd_log) 12 Exception: ls: c.py: No such file or directory 13 14 15 waterforestdeiMac:pythonCrawler waterforest$