Python模块学习 ---- subprocess 创建子进程

深入理解python中的subprocess模块 在实际开发过程中,我们经常会遇到需要从Python脚本中调用外部程序或脚本的场景。这时候,Python的subprocess模块就显得尤为重要。它是Python用来生成子进程、连接到它们的输入/输出/错误管道,以及获取它们的返回码的一个模块。本文将带你深入了解subprocess模块,学会如何高效地使用它来扩展你的Python脚本功能。subprocess模块是Python标准库的一部分,它为创建和管理子进程提供了强大的接口。在Python 2.4中引入以取代旧的模块(如os.system和。 阅读详情

  最近,我们老大要我写一个守护者程序,对服务器进程进行守护。如果服务器不幸挂掉了,守护者能即时的重启应用程序。上网Google了一下,发现Python有很几个模块都可以创建进程。最终我选择使用subprocess模块,因为在Python手册中有这样一段话:

  This module intends to replace several other, older modules and functions, such as: os.system、os.spawn*、os.popen*、popen2.*、commands.*

  subprocess被用来替换一些老的模块和函数,如:os.system、os.spawn*、os.popen*、popen2.*、commands.*。可见,subprocess是被推荐使用的模块。

 

下面是一个很简单的例子,创建一个新进程,执行app1.exe,传入相当的参数,并打印出进程的返回值:

app1.exe是一个非常简单的控制台程序,它只打印出传入的参数,代码如下:

 

  闲话少说,下面开始详细介绍subprocess模块。subprocess模块中只定义了一个类: Popen。可以使用Popen来创建进程,并与进程进行复杂的交互。它的构造函数如下:

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)

  参数args可以是字符串或者序列类型(如:list,元组),用于指定进程的可执行文件及其参数。如果是序列类型,第一个元素通常是可执行文件的路径。我们也可以显式的使用executeable参数来指定可执行文件的路径。在windows操作系统上,Popen通过调用CreateProcess()来创建子进程,CreateProcess接收一个字符串参数,如果args是序列类型,系统将会通过list2cmdline()函数将序列类型转换为字符串。
  参数bufsize:指定缓冲。我到现在还不清楚这个参数的具体含义,望各个大牛指点。
  参数executable用于指定可执行程序。一般情况下我们通过args参数来设置所要运行的程序。如果将参数shell设为True,executable将指定程序使用的shell。在windows平台下,默认的shell由COMSPEC环境变量来指定。
  参数stdin, stdout, stderr分别表示程序的标准输入、输出、错误句柄。他们可以是PIPE,文件描述符或文件对象,也可以设置为None,表示从父进程继承。
  参数preexec_fn只在Unix平台下有效,用于指定一个可执行对象(callable object),它将在子进程运行之前被调用。
  参数Close_sfs:在windows平台下,如果close_fds被设置为True,则新创建的子进程将不会继承父进程的输入、输出、错误管道。我们不能将close_fds设置为True同时重定向子进程的标准输入、输出与错误(stdin, stdout, stderr)。
  如果参数shell设为true,程序将通过shell来执行。
  参数cwd用于设置子进程的当前目录。
  参数env是字典类型,用于指定子进程的环境变量。如果env = None,子进程的环境变量将从父进程中继承。
  参数Universal_newlines:不同操作系统下,文本的换行符是不一样的。如:windows下用'/r/n'表示换,而Linux下用'/n'。如果将此参数设置为True,Python统一把这些换行符当作'/n'来处理。
  参数startupinfo与createionflags只在windows下用效,它们将被传递给底层的CreateProcess()函数,用于设置子进程的一些属性,如:主窗口的外观,进程的优先级等等。 

subprocess.PIPE

  在创建Popen对象时,subprocess.PIPE可以初始化stdin, stdout或stderr参数。表示与子进程通信的标准流。

subprocess.STDOUT

  创建Popen对象时,用于初始化stderr参数,表示将错误通过标准输出流输出。 

 

Popen的方法:

Popen.poll() 

  用于检查子进程是否已经结束。设置并返回returncode属性。

Popen.wait() 

  等待子进程结束。设置并返回returncode属性。

Popen.communicate(input=None)

  与子进程进行交互。向stdin发送数据,或从stdout和stderr中读取数据。可选参数input指定发送到子进程的参数。Communicate()返回一个元组:(stdoutdata, stderrdata)。注意:如果希望通过进程的stdin向其发送数据,在创建Popen对象的时候,参数stdin必须被设置为PIPE。同样,如果希望从stdout和stderr获取数据,必须将stdout和stderr设置为PIPE。

Popen.send_signal(signal) 

  向子进程发送信号。

Popen.terminate()

  停止(stop)子进程。在windows平台下,该方法将调用Windows API TerminateProcess()来结束子进程。

Popen.kill()

  杀死子进程。

Popen.stdin 

  如果在创建Popen对象是,参数stdin被设置为PIPE,Popen.stdin将返回一个文件对象用于策子进程发送指令。否则返回None。

Popen.stdout 

  如果在创建Popen对象是,参数stdout被设置为PIPE,Popen.stdout将返回一个文件对象用于策子进程发送指令。否则返回None。

Popen.stderr 

  如果在创建Popen对象是,参数stdout被设置为PIPE,Popen.stdout将返回一个文件对象用于策子进程发送指令。否则返回None。

Popen.pid 

  获取子进程的进程ID。

Popen.returncode 

  获取进程的返回值。如果进程还没有结束,返回None。

 下面是一个非常简单的例子,来演示supprocess模块如何与一个控件台应用程序进行交互。

 

app2.exe也是一个非常简单的控制台程序,它从界面上接收两个数值,执行加操作,并将结果打印到控制台上。代码如下:

 

 

  supprocess模块提供了一些函数,方便我们用于创建进程。

subprocess.call(*popenargs, **kwargs)

  运行命令。该函数将一直等待到子进程运行结束,并返回进程的returncode。文章一开始的例子就演示了call函数。如果子进程不需要进行交互,就可以使用该函数来创建。

subprocess.check_call(*popenargs, **kwargs) 

  与subprocess.call(*popenargs, **kwargs)功能一样,只是如果子进程返回的returncode不为0的话,将触发CalledProcessError异常。在异常对象中,包括进程的returncode信息。

 

  subprocess模块的内容就这么多。在Python手册中,还介绍了如何使用subprocess来替换一些老的模块,老的函数的例子。赶兴趣的朋友可以看一下。

 

参考文档:

subprocess — Subprocess management

PyMoTW:subprocess

Python之subprocess模块 subprocess模块是Python中用于启动和管理子进程的一个强大工具,替代了旧有的os.system和os.spawn系列函数。通过这个模块,您可以从Python脚本中执行系统命令和其他可执行程序,并与之进行交互。在Python的subprocess模块中,有一些旧的API函数,比如call()、check_call()和check_output()。这些函数在Python 3.5及更早版本中被广泛使用。 阅读详情

相关推荐

Python 中 subprocess模块的使用

文章目录前言1、subprocess模块简介一、subprocess模块的遍历函数1、call函数(1)参数命令为数组时(2)参数命令为字符串时2、check_call函数3、check_output函数 前言 subprocess在jupyter notebook中被调用时与在python 中调用会有一些不一样的地方。 1、subprocess模块简介 subprocess 模块允许我们启动一个新进程,并连接到它们的输入/输出/错误管道,从而获取返回值。 这个模块用来创建和管理子进程。它提供了高层次.

刘石头的博客 7643

【Python】python之subprocess模块详解

【Python】python之subprocess模块详解 subprocess模块 subprocess是Python 2.4中新增的一个模块,它允许你生成新的进程,连接到它们的 input/output/error 管道,并获取它们的返回(状态)码。这个模块的目的在于替换几个旧的模块和方法,如: os.system os.spawn* 1. subprocess模块中的常用函数 函数 描述 subprocess.run() Python 3.5中新增的函数。执行指定的命令,等待命令执行

qq_43331089的博客 7万+

OASIS协议标准文档的解读_第一部分

OASIS标准协议的文档的解读。完整原协议的中文翻译和解读。

洋葱的专栏 4900

Python模块学习:subprocess模块详解

args: 要执行的shell命令,默认应该是一个字符串序列,如[‘df’, ‘-Th’]或(‘df’, ‘-Th’),也可以是一个字符串,如’df -Th’,但是此时需要把shell参数的值置为True。shell: 如果shell为True,那么指定的命令将通过shell执行。如果我们需要访问某些shell的特性,如管道、文件名通配符、环境变量扩展功能,这将是非常有用的。

Python热爱者的博客 1万+

对西安交大轴承数据集XJTU-SY_Bearing_Datasets进行读取和处理:

故障诊断,对西安交大轴承数据集XJTU-SY_Bearing_Datasets进行读取和处理

qq_44757503的博客 6058

汇川PLC用户程序结构详解:如何像搭积木一样配置多任务?附EtherCAT最佳实践

本文深入解析汇川PLC用户程序结构,阐述如何像搭积木一样,通过POU、FB、FC等模块化组件高效配置多任务。文章重点结合EtherCAT通讯场景,分享了任务周期、优先级设置的最佳实践与关键避坑指南,帮助工程师构建稳定、高效的运动控制系统。

weixin_29184075的博客 537

Python模块学习:subprocess 创建子进程

原文出处:http://python.jobbole.com/81517/ 最近,我们老大要我写一个守护者程序,对服务器进程进行守护。如果服务器不幸挂掉了,守护者能即时的重启应用程序。上网Google了一下,发现Python有很几个模块都可以创建进程。最终我选择使用subprocess模块,因为在Python手册中有这样一段话: This module intends to repla

qq_33888903的博客 324

YOLOv8/v9 遥感图像目标检测实战指南:建筑物检测与变化监测

遥感图像在城市规划、灾害评估、农业监管等领域应用广泛,但传统目标检测方法存在效率低、精度不足、难以适配遥感图像大尺寸、多尺度目标等问题。本文以“建筑物检测与变化监测”为核心,基于DOTA、NWPU VHR-10等公开数据集,系统讲解YOLOv8/v9在遥感图像中的实战流程。从数据获取、格式转换、模型训练优化,到大图切片推理、建筑物变化监测,全程提供可复现的代码与参数配置。通过针对性优化(旋转增强、切片推理等),模型在NWPU VHR-10数据集上mAP50达0.85以上,可适配卫星影像、无人机航拍等多场景

专注于人工智能、软件开发、工控自动化、工厂数字化及智能化等领域,希望和大家共同进步! 519

(转)Python模块学习 ---- subprocess 创建子进程

文章来源: http://blog.youkuaiyun.com/jgood/article/details/4498166   最近,我们老大要我写一个守护者程序,对服务器进程进行守护。如果服务器不幸挂掉了,守护者能即时的重启应用程序。上网Google了一下,发现Python有很几个

laiahu的专栏 1784

人像美肤 人体美型 CVPR 2022 ABPN

人像美肤 CVPR 2022 ABPN

jacke121的专栏 841

最佳RANSAC算法拟合矩形的实现(基于PCL库)

最佳RANSAC算法是一种常用的参数估计方法,用于从数据集中拟合出最佳的模型。在计算机视觉和图像处理领域,最佳RANSAC算法常用于拟合几何形状,如矩形。本文将详细介绍如何使用点云库(PCL)中的最佳RANSAC算法来拟合矩形,并提供相应的源代码。

JbPatch的博客 1540

【python学习】基础篇-常用模块-subprocess模块:创建和管理子进程

在这个示例中,我们首先导入了subprocess模块。然后分别使用了subprocess.run()、subprocess.Popen()、subprocess.call()、subprocess.check_output()和subprocess.check_call()方法来创建和管理子进程,并执行了一些命令。在Python中,可以使用subprocess模块来创建和管理子进程。

邑轻辰的学习笔记 298

基于MATLAB的小波包分解(WPD)算法详解

本文详细介绍了基于MATLAB的小波包分解(WPD)算法。WPD作为信号处理领域的重要技术,继承并发展了小波分析的优点,通过正交镜像滤波器组将信号分解为不同频率子带,形成完整的二叉树结构。相比传统小波变换,WPD具有更精细的频带划分、自适应基选择能力和更高的灵活性,特别适合分析非平稳信号。文章系统阐述了WPD的数学原理、算法实现流程及其在机械故障诊断、生物医学信号处理等领域的应用。通过MATLAB代码示例展示了WPD的具体实现方法,并分析了不同参数设置对分解效果的影响,为工程实践提供了有价值的参考。

qq_42212808的博客 292

转:Python模块学习 ---- subprocess 创建子进程

Python模块学习 ---- subprocess 创建子进程 http://www.python.org/doc/current/library/subprocess.html 最近,我们老大要我写一个守护者程序,对服务器进程进行守护。如果服务器不幸挂掉了,守护者能即时的重启应用程序。上网Google了一下,发现Python有很几个模块都可以创建进程。最终我选择使用subp...

weixin_30267785的博客 83

EMI辐射发射超标案例

EMI辐射发射超标案例

让你爱上电路设计 8502

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

[转载]Python模块学习 ---- subprocess 创建子进程

[转自]http://blog.sciencenet.cn/blog-600900-499638.html 最近,我们老大要我写一个守护者程序,对服务器进程进行守护。如果服务器不幸挂掉了,守护者能即时的重启应用程序。上网Google了一下,发现Python有很几个模块都可以创建进程。最终我选择使用subprocess模块,因为在Python手册中有这样一段话:   This mod...

weixin_30756499的博客 204

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

上一篇: 安装Ubuntu
下一篇: pymssql访问sqlserver的一个bug
JGood
博客等级 码龄20年 498粉丝 65原创
评论 4
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值