首页 > 编程语言 >Python subprocess模块

Python subprocess模块

时间:2023-06-24 17:24:48浏览次数:56  
标签:shell obj Python stdin subprocess 模块 print True

Python subprocess模块

subprocess模块

可以执行shell命令的相关模块和函数有:

os.system 
os.spawn* 
os.popen*          --废弃
popen2.*           --废弃
commands.*      --废弃,3.x中被移除  

以上执行shell命令的相关的模块和函数的功能均在 subprocess 模块中实现,并提供了更丰富的功能。

call

执行命令,返回状态码

ret = subprocess.call(["ls", "-l"], shell=False)
ret = subprocess.call("ls -l", shell=True)  

shell = True ,允许 shell 命令是字符串形式

check_call

执行命令,如果执行状态码是 0 ,则返回0,否则抛异常

subprocess.check_call(["ls", "-l"])
subprocess.check_call("exit 1", shell=True)  

check_output

执行命令,如果状态码是 0 ,则返回执行结果,否则抛异常

subprocess.check_output(["echo", "Hello World!"])
subprocess.check_output("exit 1", shell=True)  

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与createionflags只在windows下有效将被传递给底层的CreateProcess()函数,用于设置子进程的一些属性,如:主窗口的外观,进程的优先级等等
import subprocess
ret1 = subprocess.Popen(["mkdir","t1"])
ret2 = subprocess.Popen("mkdir t2", shell=True)  

终端输入的命令分为两种:

  • 输入即可得到输出,如:ifconfig
  • 输入进行某环境,依赖再输入,如:python
import subprocess
 
obj = subprocess.Popen("mkdir t3", shell=True, cwd='/home/dev',)
import subprocess
 
obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
obj.stdin.write('print 1 \n ')
obj.stdin.write('print 2 \n ')
obj.stdin.write('print 3 \n ')
obj.stdin.write('print 4 \n ')
obj.stdin.close()
 
cmd_out = obj.stdout.read()
obj.stdout.close()
cmd_error = obj.stderr.read()
obj.stderr.close()
 
print cmd_out
print cmd_error
import subprocess
 
obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
obj.stdin.write('print 1 \n ')
obj.stdin.write('print 2 \n ')
obj.stdin.write('print 3 \n ')
obj.stdin.write('print 4 \n ')
 
out_error_list = obj.communicate()
print out_error_list
import subprocess
 
obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out_error_list = obj.communicate('print "hello"')
print out_error_list

标签:shell,obj,Python,stdin,subprocess,模块,print,True
From: https://www.cnblogs.com/evescn/p/17501349.html

相关文章

  • Python shutil模块
    Pythonshutil模块高级的文件、文件夹、压缩包处理模块将文件内容拷贝到另一个文件中,可以部分内容shutil.copyfileobj(fsrc,fdst[,length])例子importshutilf1=open("a.txt",encoding="utf-8")f2=open("b.txt","w",encoding="utf-8")shu......
  • 【python基础】文件-初识文件
    文本文件可存储的数据量是非常多的。每当需要分析或修改存储在文件中的信息时,首先就是读取文件到内存中,为此可以一次性读取文件的全部内容,也可以以每次一行的方式逐步读取。1.读取文件1.1读取整个文件要读取文件,需要一个包含几行文本的文件。下面首先来创建一个poems文本文件,,里......
  • Python os模块
    Pythonos模块os模块用于提供系统级别的操作os.getcwd()#获取当前工作目录,即当前python脚本工作的目录路径os.chdir("dirname")#改变当前脚本工作目录;相当于shell下cdos.curdir#返回当前目录:('.')os.pardir#获取当前目录......
  • Python sys模块
    Pythonsys模块sys模块用于提供对解释器相关的操作sys.argv#命令行参数List,第一个元素是程序本身路径sys.exit(n)#退出程序,正常退出时exit(0)sys.version#获取Python解释程序的版本信息sys.maxint......
  • Python hashlib模块
    Pythonhashlib模块hashlib模块用于加密相关的操作,代替了md5模块和sha模块主要提供SHA1,SHA224,SHA256,SHA384,SHA512,MD5算法#md5废弃importmd5hash=md5.new()hash.update('admin')printhash.hexdigest()#sha废弃importshahash=sha.new()ha......
  • 在 Python 中,类型属于对象,变量是没有类型的
    在Python中,类型属于对象,变量是没有类型的:━━━━━━━━━━━━━━━━━━━━━━━━━a=[1,2,3]a="w3cschool"以上代码中,[1,2,3]是list类型,"w3cschool"是string类型,而变量a是没有类型,她仅仅是一个对象的引用(一个指针),可以是list类型对象,也可以指向是stri......
  • Python 模块(转载)
    Python常用模块模块分类自定义模块开源模块内置模块自定义模块定义模块情景一情景二情景三导入模块Python之所以应用越来越广泛,在一定程度上也依赖于其为程序员提供了大量的模块以供使用,如果想要使用模块,则需要导入。导入模块有一下几种方法:importmodulefrom......
  • python: Treeview Control binding data using tkinter and ttkbootstrap GUI
     """StudentUI.py读文件类date2023-06-24edit:GeovinDu,geovindu,涂聚文ide:PyCharm2023.1python11"""importdatetimeimportsysimportosfromtkinterimportttkfromtkinterimport*fromtkinter.ttkimport*fromttk......
  • 若依微服务swagger如何不显示某个模块的接口文档?
    在若依微服务项目中,如果不想暴露某个模块的swagger的接口文档,需要怎么做?本文以ruoyi-gen模块进行举例说明。  默认情况下,可以看到这里包含了ruoyi-gen模块,我们要做的是,要将ruoyi-gen进行隐藏。最终的预期结果如下图所示,可以看见,下图中,是不包含ruoyi-gen这个模块的。那我们具体应......
  • 用python打开文件夹
    '''用python打开文件夹''''''https://blog.csdn.net/yqyangcyq/article/details/105677844'''os.system("explorer.exe%s"%str_dizh)#打开(可重复打开)目标文件夹os.startfile(str_dizh)#打开(并且屏幕上只存在一个/不会重复打开......