千家信息网

python和shell的结合与应用

发表于:2024-10-07 作者:千家信息网编辑
千家信息网最后更新 2024年10月07日,函数模块system()其中最后一个0是这个命令的返回值,为0表示命令执行成功。使用system无法将执行的结果保存起来。例子:>>> import os>>> os.system&#
千家信息网最后更新 2024年10月07日python和shell的结合与应用

函数模块

system()
  • 其中最后一个0是这个命令的返回值,为0表示命令执行成功。使用system无法将执行的结果保存起来。
    例子:
    >>> import os>>> os.system('ls')blog.tar     djangoblog.log  managerblog.sh  test.txtdata         ENV         nginx-1.15.11   wget-log0
    popen()

    提示:python3已结废弃
    例子:

    >>> import os>>> os.popen('ls')>>> os.popen('ls').read()'blog.tar\ndata\ndb.sql\ndead.letter\nDjangoBlog\ndjangoblog.log\nENV\nfile1\nget-pip.py\nindex.html\nmanagerblog.sh\nnginx-1.15.11\nPython-3.5.2\nstartDjangoBlog.sh\nstart_uwsgi.ini\ntest.txt\nwget-log\nzrlog-2.1.3-b5f0d63-release.war?attname=ROOT.war\n'>>> os.popen('ls').read().split('\n')['blog.tar', 'data', 'db.sql', 'dead.letter', 'DjangoBlog', 'djangoblog.log', 'ENV', 'file1', 'get-pip.py', 'index.html', 'managerblog.sh', 'nginx-1.15.11', 'Python-3.5.2', 'startDjangoBlog.sh', 'start_uwsgi.ini', 'test.txt', 'wget-log', 'zrlog-2.1.3-b5f0d63-release.war?attname=ROOT.war', '']

    获取命令执行的结果,但是没有命令的执行状态,这样可以将获取的结果保存起来放到list中。

subprocess
  • 可以很方便的取得命令的输出(包括标准和错误输出)和执行状态位。
  • commands.getoutput('ls')这个方法只返回执行结果result不返回状态。
    提示:subprocess模块已经取代了commands
    例子:
    1、getstatusoutput
    >>> import subprocess>>> status,result=subprocess.getstatusoutput('ls')>>> status0>>> result'blog.tar\ndata\ndb.sql\ndead.letter\nDjangoBlog\ndjangoblog.log\nENV\nfile1\nget-pip.py\nindex.html\nmanagerblog.sh\nnginx-1.15.11\nPython-3.5.2\nstartDjangoBlog.sh\nstart_uwsgi.ini\ntest.txt\nwget-log\nzrlog-2.1.3-b5f0d63-release.war?attname=ROOT.war'>>> result.split('\n')['blog.tar', 'data', 'db.sql', 'dead.letter', 'DjangoBlog', 'djangoblog.log', 'ENV', 'file1', 'get-pip.py', 'index.html', 'managerblog.sh', 'nginx-1.15.11', 'Python-3.5.2', 'startDjangoBlog.sh', 'start_uwsgi.ini', 'test.txt', 'wget-log', 'zrlog-2.1.3-b5f0d63-release.war?attname=ROOT.war']

    2、getoutput

    >>> print(subprocess.getoutput('ls').split('\n') )['blog.tar', 'data', 'db.sql', 'dead.letter', 'DjangoBlog', 'djangoblog.log', 'ENV', 'file1', 'get-pip.py', 'index.html', 'managerblog.sh', 'nginx-1.15.11', 'Python-3.5.2', 'startDjangoBlog.sh', 'start_uwsgi.ini', 'test.txt', 'wget-log', 'zrlog-2.1.3-b5f0d63-release.war?attname=ROOT.war']

    3、call
    执行命令,返回状态码(命令正常执行返回0,报错则返回1)

    >>> subprocess.call('ls')blog.tar     djangoblog.log  managerblog.sh  test.txtdata         ENV         nginx-1.15.11   wget-logdb.sql       file1       Python-3.5.2    zrlog-2.1.3-b5f0d63-release.war?attname=ROOT.wardead.letter  get-pip.py      startDjangoBlog.shDjangoBlog   index.html      start_uwsgi.ini0

4、check_call
执行命令,如果执行成功则返回状态码0,否则抛异常

>>> subprocess.check_call('ls')blog.tar     djangoblog.log  managerblog.sh  test.txtdata         ENV         nginx-1.15.11   wget-logdb.sql       file1       Python-3.5.2    zrlog-2.1.3-b5f0d63-release.war?attname=ROOT.wardead.letter  get-pip.py      startDjangoBlog.shDjangoBlog   index.html      start_uwsgi.ini0>>> subprocess.check_call('ls luojun')Traceback (most recent call last):  File "", line 1, in   File "/usr/local/python3/lib/python3.5/subprocess.py", line 576, in check_call    retcode = call(*popenargs, **kwargs)  File "/usr/local/python3/lib/python3.5/subprocess.py", line 557, in call    with Popen(*popenargs, **kwargs) as p:  File "/usr/local/python3/lib/python3.5/subprocess.py", line 947, in __init__    restore_signals, start_new_session)  File "/usr/local/python3/lib/python3.5/subprocess.py", line 1551, in _execute_child    raise child_exception_type(errno_num, err_msg)FileNotFoundError: [Errno 2] No such file or directory: 'ls luojun'

5、check_output
执行命令,如果执行成功则返回执行结果,否则抛异常

>>> subprocess.check_output('ls')b'blog.tar\ndata\ndb.sql\ndead.letter\nDjangoBlog\ndjangoblog.log\nENV\nfile1\nget-pip.py\nindex.html\nmanagerblog.sh\nnginx-1.15.11\nPython-3.5.2\nstartDjangoBlog.sh\nstart_uwsgi.ini\ntest.txt\nwget-log\nzrlog-2.1.3-b5f0d63-release.war?attname=ROOT.war\n'>>> subprocess.check_output('ls luojun')Traceback (most recent call last):  File "", line 1, in   File "/usr/local/python3/lib/python3.5/subprocess.py", line 626, in check_output    **kwargs).stdout  File "/usr/local/python3/lib/python3.5/subprocess.py", line 693, in run    with Popen(*popenargs, **kwargs) as process:  File "/usr/local/python3/lib/python3.5/subprocess.py", line 947, in __init__    restore_signals, start_new_session)  File "/usr/local/python3/lib/python3.5/subprocess.py", line 1551, in _execute_child    raise child_exception_type(errno_num, err_msg)FileNotFoundError: [Errno 2] No such file or directory: 'ls luojun'

6、subprocess.Popen(…)
用于执行复杂的系统命令
参数 注释

args shell命令,可以是字符串或者序列类型(如:list,元组)bufsize 指定缓冲。0 无缓冲,1 行缓冲,其他 缓冲区大小,负值 系统缓冲stdin, stdout, stderr 分别表示程序的标准输入、输出、错误句柄preexec_fn 只在Unix平台下有效,用于指定一个可执行对象(callable object),它将在子进程运行之前被调用close_sfs 在windows平台下,如果close_fds被设置为True,则新创建的子进程将不会继承父进程的输入、输出、错误管道。所以不能将close_fds设置为True同时重定向子进程的标准输入、输出与错误(stdin, stdout, stderr)。shell 同上cwd 用于设置子进程的当前目录env 用于指定子进程的环境变量。如果env = None,子进程的环境变量将从父进程中继承。universal_newlines 不同系统的换行符不同,True -> 同意使用 \nstartupinfo 只在windows下有效,将被传递给底层的CreateProcess()函数,用于设置子进程的一些属性,如:主窗口的外观,进程的优先级等等createionflags 同上

在python中调用shell脚本

  • 编写一个脚本,传入两个参数
    [root@VM_0_2_centos test]# vim test.sh[root@VM_0_2_centos test]# cat test.sh#!/bin/bashecho "this is my test shell ${1} ${2}"exit 0[root@VM_0_2_centos test]# chmod +x test.sh[root@VM_0_2_centos test]# /test/test.sh jluo jluocc.cnthis is my test shell jluo jluocc.cn
  • 在python脚本中调用shell脚本,并传入参数,注意参数前后要有空格
[root@VM_0_2_centos test]# vim mytest.py[root@VM_0_2_centos test]# cat mytest.py #! /usr/bin/env python3import osimport sysif(len(sys.argv)<3):    print("please input two arguments")    sys.exit(1)arg0 = sys.argv[1]arg1 = sys.argv[2]print('=====file name *.py全路径=====')print(sys.argv[0])print('=====脚本执行结果如下=====')os.system('/test/test.sh '+arg0+' '+arg1)[root@VM_0_2_centos test]# python3 mytest.py jluo jluocc.cn=====file name *.py全路径=====mytest.py=====脚本执行结果如下=====this is my test shell jluo jluocc.cn[root@VM_0_2_centos test]# python3 /test/mytest.py jluo jluocc.cn=====file name *.py全路径=====/test/mytest.py=====脚本执行结果如下=====this is my test shell jluo jluocc.cn

结束语:
更多精彩内容持续更新中,关注微信公众号,有你更精彩。

0