您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

Python下的subprocess模块的入门指引

2024/3/4 23:22:12发布28次查看
在熟悉了qt的qprocess以后,再回头来看python的subprocess总算不觉得像以前那么恐怖了。
和qprocess一样,subprocess的目标是启动一个新的进程并与之进行通讯。
subprocess.popen
这个模块主要就提供一个类popen:
class subprocess.popen( args, bufsize=0, executable=none, stdin=none, stdout=none, stderr=none, preexec_fn=none, close_fds=false, shell=false, cwd=none, env=none, universal_newlines=false, startupinfo=none, creationflags=0)
这堆东西真让人抓狂:
subprocess.popen([gedit,abc.txt])subprocess.popen(gedit abc.txt)
这两个之中,后者将不会工作。因为如果是一个字符串的话,必须是程序的路径才可以。(考虑unix的api函数 exec,接受的是字符串列表)
但是下面的可以工作
subprocess.popen(gedit abc.txt, shell=true)
这是因为它相当于
subprocess.popen([/bin/sh, -c, gedit abc.txt])
都成了sh的参数,就无所谓了
在windows下,下面的却又是可以工作的
subprocess.popen([notepad.exe, abc.txt])subprocess.popen(notepad.exe abc.txt)
这是由于windows下的api函数createprocess接受的是一个字符串。即使是列表形式的参数,也需要先合并成字符串再传递给api函数。
类似上面
subprocess.popen(notepad.exe abc.txt shell=true)
等价于
subprocess.popen(cmd.exe /c +notepad.exe abc.txt shell=true)subprocess.call*
模块还提供了几个便利函数(这本身也算是很好的popen的使用例子了)
call() 执行程序,并等待它完成
def call(*popenargs, **kwargs): return popen(*popenargs, **kwargs).wait()
check_call() 调用前面的call,如果返回值非零,则抛出异常
def check_call(*popenargs, **kwargs): retcode = call(*popenargs, **kwargs) if retcode: cmd = kwargs.get(args) raise calledprocesserror(retcode, cmd) return 0
check_output() 执行程序,并返回其标准输出
def check_output(*popenargs, **kwargs): process = popen(*popenargs, stdout=pipe, **kwargs) output, unused_err = process.communicate() retcode = process.poll() if retcode: cmd = kwargs.get(args) raise calledprocesserror(retcode, cmd, output=output) return output
popen对象
该对象提供有不少方法函数可用。而且前面已经用到了wait()/poll()/communicate()
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product