当前位置: 首页 > news >正文

python subprocess使用_python subprocess使用-阿里云开发者社区

shell中可以很方便的调用其它应用程序,将不同的应用程序组合组合起来。

python通过subprocess模块也能实现类似功能。

因为python拥有丰富的数据接口,简洁的语法,让python在进行类似的工作时比shell更容易维护。

subprocess模块是在python2.4的时候引入。详细信息查看PEP 324

介绍

subprocess主要有以下几个函数:

call(args, *, stdin=None, stdout=None, stderr=None, shell=False, timeout=None)

check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False, timeout=None)

check_output(args, *, input=None, stdin=None, stderr=None, shell=False, universal_newlines=False, timeout=None)这些函数底层都是使用Popen 类,该类拥有的方法和属性有有:

poll()

wait(timeout=None) #timeout python3.3开始引入

communicate(input=None, timeout=None)

send_signal(signal)

terminate()

kill()

args

stdin

stdout

stderr

pid

returncode

例子

当前例子环境为:python3.4+windows10。

主要为了实现:python调用mysql,向mysql传递命令,获取mysql执行之后的结果。

方法1:

通过变量传递和保存输入输出,使用Popen

def test1():

child1=subprocess.Popen(['mysql','-udemo','-pdemo'],stdin=subprocess.PIPE,stdout=subprocess.PIPE)

(stdout,stderr)=child1.communicate(input=b'use demo;\n show tables;\nexit\n')

print(stdout.decode())方法1还有一种写法,直接向stdin写入命令,直接从stdout读出结果:

def test11():

child1=subprocess.Popen(['mysql','-udemo','-pdemo'],stdin=subprocess.PIPE,stdout=subprocess.PIPE)

child1.stdin.write(b'use demo;\n show tables;\nexit\n');

child1.stdin.close()

print(child1.stdout.read().decode())

child1.stdout.close()

方法2:

通过变量传递输入,将输出保存到文件中,使用Popen

def test2():

outfile=r'result.txt'

child1=subprocess.Popen(['mysql','-udemo','-pdemo','-s'],stdin=subprocess.PIPE,stdout=open(outfile,'wb'))

child1.communicate(input=b'use demo;\n show tables;\nexit\n')

if child1.returncode==0:

with open(outfile) as f:

print(f.read())

方法3:

通过文件传递输入,将输出保存到文件中,使用Popen

def test3():

infile=r'sql.txt'

outfile=r'result.txt'

child1=subprocess.Popen(['mysql','-udemo','-pdemo','-s','-h172.16.1.141'],stdin=open(infile,'rb'),stdout=open(outfile,'wb'))

print('input:')

with open(infile) as f:

print(f.read())

print('output:')

with open(outfile) as f:

print(f.read())对于方法3,还有另外一种写法,使用call:

def test31():

infile=r'sql.txt'

outfile=r'result.txt'

result_code=subprocess.call(['mysql','-udemo','-pdemo','-s','-h172.16.1.141'],stdin=open(infile,'rb'),stdout=open(outfile,'wb'))

print('input:')

with open(infile) as f:

print(f.read())

if result_code==0:

print('output:')

with open(outfile) as f:

print(f.read())

一些参数说明:

Popen(args, bufsize=-1, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=True, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0, restore_signals=True, start_new_session=False, pass_fds=())中的stdin,stdout,stderr需要是PIPE, DEVNULL, None或者是file descriptor 。

如果传入的参数是PIPE,那么Popen会自己建立一个pipe,可以把这个pipe当做一个文件,stdin可以往里面写(写完命令之后,注意close),stdout可以从里面读。参考test11()

如果stdin是file descriptor ,需要文件中有准备好的内容,因为进程在执行的时候,会直接从这个文件中读取数据。参考test3()或test31()

Popen.communicate(input=None, timeout=None) 中的input需要是None,或者bytes(如果universal_newlines =True,可以是string),这个函数只能调用一次,调用之后会一直等待,直到进程停止。

总结

如果是一些简单的调用,执行使用call、check_call、check_output就行了。

如果需要更精细的控制,使用Popen可以完成。如果是进程间的通信,使用PIPE,如果仅仅传入一些命令,使用文件或者communicate中的input既可。

以上是一个例子,真正和MySQL交互的时候可以使用其提供的客户端mysql-connector直接进行交互 。

相关文章:

  • tomcat日志神器--kibana
  • python计算相同生日概率_用python计算下一个生日前的天数
  • java保证多线程的执行顺序
  • php 文本显示一部分_使用简单,功能全面的 PHP 命令行应用库
  • jzoj4196 二分图计数 解题报告(容斥原理)
  • 华为上半年手机销量_国产手机上半年销量出炉:小米华为所向无敌
  • Python2与Python3区别
  • 计算混响时间的意义_计算你房间的混响时间
  • cordova打开文件_cordova插件之下载文件并打开
  • Fragment切换返回
  • kylin 大数据架构_Kylin对大数据量的多维分析
  • 17-----案例
  • l130 华大低功耗mcu_HC32L110C6PA HC32L110C6UA 华大超低功耗 Cortex-M0+ 32位MCU
  • springmvc拦截器对请求参数解密_springMvc使用拦截器自定义处理参数
  • 2017-2018 ACM-ICPC Northern Eurasia (Northeastern European Regional) Contest (NEERC 17) 日常训练...
  • Git初体验
  • JavaWeb(学习笔记二)
  • js数组之filter
  • Laravel 菜鸟晋级之路
  • MySQL Access denied for user 'root'@'localhost' 解决方法
  • MySQL数据库运维之数据恢复
  • open-falcon 开发笔记(一):从零开始搭建虚拟服务器和监测环境
  • react-native 安卓真机环境搭建
  • Solarized Scheme
  • spring-boot List转Page
  • Web设计流程优化:网页效果图设计新思路
  • 初识 webpack
  • 飞驰在Mesos的涡轮引擎上
  • 罗辑思维在全链路压测方面的实践和工作笔记
  • 前端技术周刊 2019-01-14:客户端存储
  • 小试R空间处理新库sf
  • 函数计算新功能-----支持C#函数
  • 通过调用文摘列表API获取文摘
  • # 日期待t_最值得等的SUV奥迪Q9:空间比MPV还大,或搭4.0T,香
  • ###项目技术发展史
  • #HarmonyOS:Web组件的使用
  • (+4)2.2UML建模图
  • (2009.11版)《网络管理员考试 考前冲刺预测卷及考点解析》复习重点
  • (3)nginx 配置(nginx.conf)
  • (3)选择元素——(14)接触DOM元素(Accessing DOM elements)
  • (MonoGame从入门到放弃-1) MonoGame环境搭建
  • (动手学习深度学习)第13章 计算机视觉---图像增广与微调
  • (二)fiber的基本认识
  • (附源码)springboot宠物医疗服务网站 毕业设计688413
  • (附源码)springboot建达集团公司平台 毕业设计 141538
  • (附源码)springboot助农电商系统 毕业设计 081919
  • (附源码)ssm基于jsp的在线点餐系统 毕业设计 111016
  • (原创)攻击方式学习之(4) - 拒绝服务(DOS/DDOS/DRDOS)
  • (转)淘淘商城系列——使用Spring来管理Redis单机版和集群版
  • (转载)OpenStack Hacker养成指南
  • .[backups@airmail.cc].faust勒索病毒的最新威胁:如何恢复您的数据?
  • .NET BackgroundWorker
  • .NET CORE 2.0发布后没有 VIEWS视图页面文件
  • .NET MVC、 WebAPI、 WebService【ws】、NVVM、WCF、Remoting
  • .NET 的静态构造函数是否线程安全?答案是肯定的!