Last active
December 15, 2018 07:33
-
-
Save ayuLiao/03a0b2d7bee444fd9dc6fd945428ae6b to your computer and use it in GitHub Desktop.
python执行shell脚本有多种方法,这里展示个人常用的两种 1. 使用 python的 command库
2.使用subprocess 库
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ''' | |
| 使用commdans执行shell命令 | |
| 这种方式不会创建独立进程去执行shell命令,即python程序退出,shell命令启动的程序也就退出了 | |
| 这种方式适合于短时任务,即不是后台进程型任务 | |
| python2才会有 | |
| ''' | |
| def execshell(self, shell): | |
| exit_status, output = commands.getstatusoutput(shell) | |
| if int(exit_status) == 0: | |
| print('%s execute success!'%shell) | |
| else: | |
| print('%s execute error: exit_status [%s] err [%s]' % (shell, str(exit_status), output)) | |
| # if shell error , exit python program | |
| exit() | |
| return exit_status, output | |
| ''' | |
| 使用subprocess的Popen来执行shell命令,这种方式会创建一个新的进程来执行shell | |
| 使用要放在后台一直执行的shell进程,比如通过shell启动某种服务,如果通过上面 | |
| 的方式,就会遇到当python被关闭时,shell启动的程序也被关闭 | |
| 需要注意的是close_fds参数,默认为false,表示继承fb,即文件资源符,如果继承fb,那么当父进程关闭时 | |
| shell启动的子进程会去继承父进程相应的资源,如Flask web服务中通过shell启动了某个服务,此时Flask关闭了 | |
| 但原本Flask监听的端口依旧会被shell子进程占用,这样就导致Flask无法再次启动。 | |
| 将close_fds设置为false可以避免这种情况 | |
| ''' | |
| def execshell2(self,shell): | |
| try: | |
| p = subprocess.Popen(shell, shell=True,stdout=subprocess.PIPE ,stderr=subprocess.STDOUT, close_fds=True) | |
| output = p.stdout.read() | |
| # p.terminate() | |
| code = 0 | |
| print('%s execute success!' % shell) | |
| except subprocess.CalledProcessError as e: | |
| code = e.returncode | |
| output = e.output | |
| print('%s execute error: exit_status [%s] err [%s]' % (shell, str(code), output)) | |
| exit() | |
| return code, output |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment