subprocess.Popen()


新进小白

 

写了一个python脚本执行linux命令"df -h"

第一次:

#!/bin/python

import subprocess

def main():

  p = subprocess.Popen('df-h',shell=True,stdout.PIPE,stderr=subprocess.STDOUT)

main()

执行完成后:

SyntaxError:non-keyword arg after keyword arg。Python中调用函数时,有时会报SyntaxError: non-keyword arg after keyword arg错误。
这通常是因为函数中定义了部分参数的默认值,Python中*arg表示任意多个无名参数,类型为tuple(元组),**kwargs表示关键字参数,为dict(字典),因此没有默认值的参数,即*arg 要放在前面,**kwargs 要放在后面,出现这个错误后,可以在有默认值的参数前加上参数名即可
这里是因为p = subprocess.Popen('df-h',shell=True,stdout.PIPE,stderr=subprocess.STDOUT)含有默认的函数数值,如stdout.PIPE,应修改成stdout=subprocess.PIPE

修改完成后:成功

 

但是我想把命令返回结果输出到屏幕上:

第二次:

#!/bin/python

import subprocess

def main():

  p = subprocess.Popen('df-h',shell=True,stdout.PIPE,stderr=subprocess.STDOUT)

  print p

main()

执行结果:

<subprocess.Popen object at 0x7f33391b2a10>,这是因为subprocess.Popen返回值需要read出来

修改后:

#!/bin/python

import subprocess

def main():

  p = subprocess.Popen('df-h',shell=True,stdout.PIPE,stderr=subprocess.STDOUT)

  out = p.stdout.readlines()

  print out

main()

输出结果:没有用分行,所有的字符堆积在一起。要想一行一行的打印,需要使用strip()函数

修改后:

#!/bin/python

import subprocess

def main():

  p = subprocess.Popen('df-h',shell=True,stdout.PIPE,stderr=subprocess.STDOUT)

  out = p.stdout.readlines() 

  for line in out : 

    print line.strip():

main()

输出结果会一行一行的清晰分出来。

 

若是想把df -h结果输出到一个文件:

第三次:

#!/bin/python

import subprocess

import os

def main():

  p = subprocess.Popen('df-h',shell=True,stdout.PIPE,stderr=subprocess.STDOUT)

  out = p.stdout.readlines() 

  for line in out : 

    data = line.strip()

    file = open('test.txt','a+')

    file.writelines(data+"\n")   #加"+\n"是为了实现把文本里面的内容行行转译

    file.close

main()

 

关于subprocess.Popen的使用可以具体的看以下链接:https://www.cnblogs.com/zhoug2020/p/5079407.html

关于strip()函数的使用可以看以下链接:http://www.runoob.com/python/att-string-strip.html


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM