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的结合与应用

相关内容

热门资讯

雷达、机库、营房、燃料库、飞机... 据《华盛顿邮报》5月6日报道,通过卫星影像分析发现,自2月28日战事爆发以来,伊朗空袭已在中东美军军...
从买买买到租租租,“租用一代”... “五一”假期还在路上,年轻人已经“租”起来了。 “租三天,不到300块钱。”五一放假前一周,清清已给...
【品牌】摩托罗拉大折叠屏新机定... 此前联想预热将于5月19日19点举行联想天禧AI一体多端全场景新品超能之夜活动,届时将带来多款新品,...
常州欣隽益取得接线端子用快速冲... 国家知识产权局信息显示,常州欣隽益科技有限公司取得一项名为“接线端子用快速冲切装置”的专利,授权公告...
美媒:特朗普在结束伊朗战争问题... 据“国会山”网站5月6日报道,周二晚间,美国总统特朗普突然宣布终止旨在打破伊朗对霍尔木兹海峡掌控的军...
和创硅材料取得熔融石英制品擦洗... 国家知识产权局信息显示,东海县和创硅材料有限公司取得一项名为“一种熔融石英制品的擦洗脱泥装置”的专利...
美商务部长再就爱泼斯坦案接受国... 5月6日,美国商务部长卢特尼克“自愿”就其与爱泼斯坦的关系接受美国国会众议院监督与政府改革委员会的问...
“五一”小长假黄金零售市场新变... 【大河财立方 记者 孙凯杰】 “五一”小长假,黄金价格出现一波短暂调整,线下黄金零售市场热度如何?5...
以军3周来首次袭击黎巴嫩首都 据以色列总理内塔尼亚胡和国防部长卡茨当地时间5月6日晚发表的联合声明,以军当天对黎巴嫩首都贝鲁特南郊...
东莞移动:5G-A智擎护航, ... “五一”期间,松山湖草莓音乐节、广东国际汽车展示交易会·春季、2026茶园游会田园文化美食节、大岭山...