python和shell的结合与应用
admin
2023-02-24 23:00:04
0次

函数模块

system()
  • 其中最后一个0是这个命令的返回值,为0表示命令执行成功。使用system无法将执行的结果保存起来。
    例子:
    >>> import os
    >>> os.system('ls')
    blog.tar     djangoblog.log  managerblog.sh  test.txt
    data         ENV         nginx-1.15.11   wget-log
    0
    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')
    >>> status
    0
    >>> 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.txt
    data         ENV         nginx-1.15.11   wget-log
    db.sql       file1       Python-3.5.2    zrlog-2.1.3-b5f0d63-release.war?attname=ROOT.war
    dead.letter  get-pip.py      startDjangoBlog.sh
    DjangoBlog   index.html      start_uwsgi.ini
    0

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

>>> subprocess.check_call('ls')
blog.tar     djangoblog.log  managerblog.sh  test.txt
data         ENV         nginx-1.15.11   wget-log
db.sql       file1       Python-3.5.2    zrlog-2.1.3-b5f0d63-release.war?attname=ROOT.war
dead.letter  get-pip.py      startDjangoBlog.sh
DjangoBlog   index.html      start_uwsgi.ini
0
>>> 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 -> 同意使用 \n
startupinfo 只在windows下有效,将被传递给底层的CreateProcess()函数,用于设置子进程的一些属性,如:主窗口的外观,进程的优先级等等
createionflags 同上

在python中调用shell脚本

  • 编写一个脚本,传入两个参数
    [root@VM_0_2_centos test]# vim test.sh
    [root@VM_0_2_centos test]# cat test.sh
    #!/bin/bash
    echo "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.cn
    this 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 python3
import os
import sys

if(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

结束语:
更多精彩内容持续更新中,关注微信公众号,有你更精彩。
python和shell的结合与应用

相关内容

热门资讯

空调连续工作多久需要停机休息 空调连续工作的时间取决于多个因素,包括空调的型号、功率、使用环境和维护情况等。一般来说,空调可以连续...
空调哪个符号是除湿的 空调除湿功能通常用一个水滴形状的符号表示。不同品牌和型号的空调遥控器可能会有所差异,但一般来说,除湿...
格力空调多长时间加一次氟利昂 1、一般情况下,空调对氟利昂的使用量是非常小的,所以在空调使用了四年左右的时候再考虑加也没问题。2、...
空调用多长时间需要加氟一次 一般情况下是五年。当出现以下这几种情况时,空调才需要加氟。1、空调的室内机和室外机各有两个接口,当接...
格调生活·C标思享荟:卡萨帝在... 9月12日的郑州龙湖金融岛,夜风轻拂,灯光璀璨。“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑...
品牌价值破千亿、高端份额持续领... 9月12日,“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑州站”在郑州龙湖金融岛举办。2026...
空调主板坏了修800还是换新的 空调主板坏了是修还是换新,需要考虑多个因素,以下是一些建议:1. 维修成本:如果维修费用较低,比如 ...
空调开多久需要休息多长时间 问题:空调开多久需要休息多长时间回答:1、在使用空调的过程中,一般空调开7~8个小时左右需要休息2~...
中央空调多长时间清洗一次 1、一般空调开机前清洗一次即可,空调开机中间时段再清洗一次,空调关机时清洗一次,这样比较合理。2、空...
中央空调氟利昂多久加一次 看空调制热和制冷程度,很多人的观点认为氟利昂必须一年放一次,其实这个观点是错误的,理解上面有点偏差,...