当前位置: 首页 > 编程笔记 >

日常整理python执行系统命令的常见方法(全)

公羊向荣
2023-03-14
本文向大家介绍日常整理python执行系统命令的常见方法(全),包括了日常整理python执行系统命令的常见方法(全)的使用技巧和注意事项,需要的朋友参考一下

具体内容如下:

1 os.system

例如 ipython中运行如下命令,返回运行状态status

os.system('cat /etc/passwdqc.conf')
min=disabled,24,11,8,7
max=40
passphrase=3
match=4
similar=deny
random=47
enforce=everyone
retry=3
Out[6]: 0

2 os.popen()

popen(command [, mode='r' [, bufsize]]) -> pipe
Open a pipe to/from a command returning a file object.

运行返回结果

In [20]: output = os.popen('cat /proc/cpuinfo')
In [21]: lineLen = []
In [22]: for line in output.readlines():
    lineLen.append(len(line))
   ....:    
In [23]: line
line     lineLen 
In [23]: lineLen
Out[23]:
[14,
 25,
...

3 如何同时返回结果和运行状态,commands模块:

#String form: <module 'commands' from '/usr/lib64/python2.7/commands.pyc'>
File: /usr/lib64/python2.7/commands.py
Docstring:
Execute shell commands via os.popen() and return status, output.
Interface summary:
import commands
outtext = commands.getoutput(cmd)
(exitstatus, outtext) = commands.getstatusoutput(cmd)
outtext = commands.getstatus(file) # returns output of "ls -ld file"
A trailing newline is removed from the output string.
Encapsulates the basic operation:
pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r')
text = pipe.read()
sts = pipe.close()

commands示例如下:

In [24]: (status, output) = commands.getstatusoutput('cat /proc/cpuinfo')
In [25]: status
Out[25]: 0
In [26]: len(output)
Out[26]: 3859

4 使用模块subprocess

ipython 中运行"?subprocess"可以发现subprocess是python用来替换os.popen()等管道操作命令的新模块

A more real-world example would look like this:

try:
 retcode = call("mycmd" + " myarg", shell=True)
 if retcode < 0:
  print >>sys.stderr, "Child was terminated by signal", -retcode
 else:
  print >>sys.stderr, "Child returned", retcode
except OSError, e:
 print >>sys.stderr, "Execution failed:", e

相对于上面几种方式,subprocess便于控制和监控进程运行结果,subprocess提供多种函数便于应对父进程对子进程不同要求:

4.1.1 subprocess.call()

父进程父进程等待子进程完成,返回exit code

4.1.2 subprocess.check_call()

父进程等待子进程完成,返回0,如果returncode不为0,则举出错误subprocess.CalledProcessError,该对象包含有returncode属性,可用try...except...来检查

4.1.3 subprocess.check_output()

父进程等待子进程完成

返回子进程向标准输出的输出结果

检查退出信息,如果returncode不为0,则举出错误subprocess.CalledProcessError,该对象包含有returncode属性和output属性,output属性为标准输出的输出结果,可用try...except...来检查

例如:

In [32]: out = subprocess.call("ls -l", shell=True)
total 42244
-rw-rw-r--.  1 *** ***     366 May 26 09:10 ChangeLog

4.2.1

上面三个函数都是源于Popen()函数的wapper(封装),如果需要更加个性化应用,那么就需要使用popen()函数

Popen对象创建后,主程序不会自动等待子进程完成。我们必须调用对象的wait()方法,父进程才会等待 (也就是阻塞block)

[wenwt@localhost syntax]$ rm subprocess.pyc 
[wenwt@localhost syntax]$ python process.py 
parent process
[wenwt@localhost syntax]$ PING www.google.com (173.194.219.99) 56(84) bytes of data.
^C
[wenwt@localhost syntax]$ 
--- www.google.com ping statistics ---
5 packets transmitted, 0 received, 100% packet loss, time 3999ms

加上wait方法:

[wenwt@localhost syntax]$ python process.py 
PING www.google.com (173.194.219.103) 56(84) bytes of data.
--- www.google.com ping statistics ---
5 packets transmitted, 0 received, 100% packet loss, time 3999ms
parent process

补充介绍:Python 执行终端命令的方法

import os
import subprocess
'''
os.system模块
os.system("ls -hl") 执行命令并返回状态码,当返回0表示成功;返回256表示失败,痛点是无法返回output
os.popen模块
os.popen("ls -hl") 执行命令,之后通过.read()方法获取output返回值
subprocess模块
subprocess.getstatusoutput("ls -hl") 执行命令,并返回状态status、输出output
subprocess.getoutput("ls -hl")    执行命令,只返回输出结果output
subprocess.call("ls -hl")      执行命令并返回状态码 和os.system("ls -hl")类似
'''
def test_system(cmd):
  status = os.system(cmd) # 会自动输出output到控制台 但是无法接收,status为0表示成功、status为256表示失败
  print(status)
def test_popen(cmd):
  output = os.popen(cmd).read() # 只会获取到命令的output,如果是有output的错误命令 会输出output,否则输出空白
  print(output)
def test_getoutput(cmd):
  output = subprocess.getoutput(cmd) # 和os.popen(cmd)类似
  print(output)
def test_getstatusoutput(cmd):
  status, output = subprocess.getstatusoutput(cmd) # 执行命令,并返回状态status、输出output
  print(status)
  print(output)
def test_call(cmd):
  status = subprocess.call(cmd) # 和os.system(cmd)类似
  print(status)
if __name__ == '__main__':
  # test_system('ls -lh') # test_system('test')
  # test_popen('pwd') # test_popen('test')
  # test_getoutput('pwd')
  # test_getstatusoutput('pwd')
  test_call('pwd')

以上内容就是本文的全部叙述,希望大家喜欢。

 类似资料:
  • 本文向大家介绍Python执行Linux系统命令的4种方法,包括了Python执行Linux系统命令的4种方法的使用技巧和注意事项,需要的朋友参考一下 (1) os.system 仅仅在一个子终端运行系统命令,而不能获取命令执行后的返回信息 如果再命令行下执行,结果直接打印出来 (2) os.popen 该方法不但执行命令还返回执行后的信息对象 例如: 好处在于:将返回的结果赋于一变量,便于程序的

  • 本文向大家介绍Go语言执行系统命令行命令的方法,包括了Go语言执行系统命令行命令的方法的使用技巧和注意事项,需要的朋友参考一下 本文实例讲述了Go语言执行系统命令行命令的方法。分享给大家供大家参考。具体如下: 执行Go代码时可以附加参数,包括要执行的命令和给命令的参数 希望本文所述对大家的Go语言程序设计有所帮助。

  • 本文向大家介绍Lua中执行系统命令方法介绍,包括了Lua中执行系统命令方法介绍的使用技巧和注意事项,需要的朋友参考一下 Lua中,os.execute可以执行dos命令,但是返回的是系统状态码,默认输出。 io.popen()也可以执行dos命令,但是返回一个文件。eg: 如果想执行某命令或程序可选os.execute(),如果还想捕捉该执行结果可用io.popen() eg:复制文件

  • 本文向大家介绍redis常用命令整理,包括了redis常用命令整理的使用技巧和注意事项,需要的朋友参考一下 一、key 相关: (1)redis允许模糊查询 key(keys *)  有3个通配符 *、?、[] (2)randomkey:返回随机key   (3)type key:返回key存储的类型 (4)exists key:判断某个key是否存在 (5)del key:删除key FLUSH

  • 笔者在前面介绍的内容都为linux系统基础类的,如果你现在把前面的内容全部很好的掌握了,那最好了。不过笔者要说的是,即使你完全掌握了,你现在还是不能作为一名合格的linux系统管理员的,毕竟系统管理员要会做的事情太多了。本章以及后面章节笔者会陆续教给你作为linux系统管理员所必备的知识。只要你熟练掌握那绝对可以胜任一个最初级的管理员职位,不过只是初级的,因为你还需要在日常的管理工作中获得成长。

  • 主要内容:1.列出Mysql数据库,2.列出Mysql数据库,3.将Mysql导入hdfs,4.hdfs到Mysql导出,5.hbase - mysql,6.job1.列出Mysql数据库 2.列出Mysql数据库 3.将Mysql导入hdfs 4.hdfs到Mysql导出 注意 需要提前在mysql创建表 5.hbase - mysql 由于没有提供接口所以采用迂回的方法传输数据, hbase - hdfs - mysql 6.job 作业相当于一个可以执行的任务也可以不执行。可以放在那里不执