python类库31[进程subprocess]

python类库31[进程subprocess]

 

 

subprocess.Popen用来创建子进程。

 

1)Popen启动新的进程与父进程并行执行,默认父进程不等待新进程结束。

def  TestPopen():
  
import  subprocess
  p
= subprocess.Popen( " dir " ,shell = True)
  
for  i  in  range( 250 ) :
    
print  ( " other things " )
复制代码

 

2)p.wait函数使得父进程等待新创建的进程运行结束,然后再继续父进程的其他任务。且此时可以在p.returncode中得到新进程的返回值。

def  TestWait():
  
import  subprocess
  
import  datetime
  
print  (datetime.datetime.now())
  p
= subprocess.Popen( " sleep 10 " ,shell = True)
  p.wait()
  
print  (p.returncode)
  
print  (datetime.datetime.now())
复制代码

 

3) p.poll函数可以用来检测新创建的进程是否结束。

def  TestPoll():
  
import  subprocess
  
import  datetime
  
import  time
  
print  (datetime.datetime.now())
  p
= subprocess.Popen( " sleep 10 " ,shell = True)
  t 
=   1
  
while (t  <=   5 ):
    time.sleep(
1 )
    p.poll()
    
print  (p.returncode)
    t
+= 1
  
print  (datetime.datetime.now())
复制代码

 

4) p.kill或p.terminate用来结束创建的新进程,在windows系统上相当于调用TerminateProcess(),在posix系统上相当于发送信号SIGTERM和SIGKILL。

def  TestKillAndTerminate():
    p
= subprocess.Popen( " notepad.exe " )
    t 
=   1
    
while (t  <=   5 ):
      time.sleep(
1 )
      t 
+= 1
    p.kill()
    
# p.terminate()
     print  ( " new process was killed " )
复制代码

  

5) p.communicate可以与新进程交互,但是必须要在popen构造时候将管道重定向。

def  TestCommunicate():
  
import  subprocess
  cmd 
=   " dir "
  p
= subprocess.Popen(cmd, shell = True, stdout = subprocess.PIPE, stderr = subprocess.STDOUT)
  (stdoutdata, stderrdata) 
=  p.communicate()
  
  
if  p.returncode  !=  0:
        
print  (cmd  +   " error ! " )
  
# defaultly the return stdoutdata is bytes, need convert to str and utf8
   for  r  in  str(stdoutdata,encoding = ' utf8 '  ).split( " \n " ):
    
print  (r)
  
print  (p.returncode)

def  TestCommunicate2():
  
import  subprocess
  cmd 
=   " dir "
  
# universal_newlines=True, it means by text way to open stdout and stderr
  p  =  subprocess.Popen(cmd, shell = True, universal_newlines = True, stdout = subprocess.PIPE, stderr = subprocess.STDOUT)
  curline 
=  p.stdout.readline()

  
while (curline  !=   "" ):
        
print  (curline)
        curline 
=  p.stdout.readline()
  p.wait()
  
print  (p.returncode)
复制代码

 

 

6) call函数可以认为是对popen和wait的分装,直接对call函数传入要执行的命令行,将命令行的退出code返回。

def  TestCall():
  retcode 
=  subprocess.call( " c:\\test.bat " )
  
print  (retcode)
复制代码

 

7)subprocess.getoutput 和 subprocess.getstatusoutput ,基本上等价于subprocess.call函数,但是可以返回output,或者同时返回退出code和output。

但是可惜的是好像不能在windows平台使用,在windows上有如下错误:'{'isnot recognized as an internalor external command, operable program or batch file. 

def  TestGetOutput():
  outp 
=  subprocess.getoutput( " ls -la " )
  
print  (outp)

def  TestGetStatusOutput():
  (status, outp) 
=  subprocess.getstatusoutput( ' ls -la ' )
  
print  (status)
  
print  (outp)
复制代码

 

8)总结

popen的参数,第一个为字符串(或者也可以为多个非命名的参数),表示你要执行的命令和命令的参数;后面的均为命名参数;shell=True,表示你前面的传入的命令将在shell下执行,如果你的命令是个可执行文件或bat,不需要指定此参数;stdout=subprocess.PIPE用来将新进程的输出重定向,stderr=subprocess.STDOUT将新进程的错误输出重定向到stdout,stdin=subprocess.PIPE用来将新进程的输入重定向;universal_newlines=True表示以text的方式打开stdout和stderr。 

 

其他的不推荐使用的模块:

os.system
os.spawn*
os.popen*
popen2.*
commands.*

 

参考:

http://www.liuzhongshu.com/code/subprocess-detail.html

http://www.liuzhongshu.com/code/python-vs-bat.html

感谢,Thanks!

作者:iTech
出处:http://itech.cnblogs.com/

转载于:https://www.cnblogs.com/SophiaTang/archive/2012/03/09/2387296.html

相关推荐

使用Metasploit生成木马控制Windows系统

使用Metasploit生成木马控制Windows系统

weixin_56956399的博客 2508

python之subprocess模块

1.subprocess用来生成子进程,并可通过管道连接输入、输出、错误,并获得其返回值,subprocess提供了一些管理标准流(standard stream)和管道(PIPE)的工具,供进程间使用文本通信 2.subprocess常用函数:run、call、check_call、check_putput、getoutput、getstatusoutput run: subp...

zaygee的博客 403

STM32 CAN发送丢包?3个邮箱轮询法实测有效(附代码)

本文深入分析了STM32 CAN总线发送丢包的根本原因,指出其内置CAN控制器的三个发送邮箱是硬件瓶颈。针对高负载场景,提供了实测有效的优化方案,重点介绍了非阻塞的邮箱状态轮询法,该方法通过主动轮询三个邮箱的空闲状态,充分利用硬件资源,显著提升发送稳定性并避免任务阻塞。文中附有可直接使用的示例代码。

weixin_29189381的博客 195

subprocess模块详解

原文地址 Python多进程方面涉及的模块主要包括: subprocess:可以在当前程序中执行其他程序或命令; mmap:提供一种基于内存的进程间通信机制; multiprocessing:提供支持多处理器技术的多进程编程接口,并且接口的设计最大程度地保持了和threading模块的一致,便于理解和使用。 本文主要介绍 subprocess 模块及其提供的 Popen 类,以及如何使用...

Python进程管理工具 Supervisor 使用教程 4367

[模型部署]-[LLM]昇腾部署Qwen3-Coder-30B-A3B-Instruct

摘要:本文介绍了在Ascend NPU上部署Qwen3-Coder-30B-A3B-Instruct大模型的实践过程。通过vLLM-Ascend框架,详细说明了环境准备(CANN 8.1、PyTorch-NPU 2.5.1等)、模型下载、容器启动及服务部署步骤,包括vLLM服务的启动参数配置和接口测试方法。测试结果显示在当前2卡910B3配置下性能表现仅为8token/s(1并发),并指出流式调用时存在无法输出usage信息的问题。该方案为Ascend平台私有化部署大模型推理服务提供了参考实现。

1670

模拟滤波器的基础知识和设计

使用Python实现多种模拟滤波器

faltas的博客 3529

【process.popen】

process.popen学习

weixin_63016274的博客 632

基于ESP32与JavaScript的Stack-chan桌面机器人:从硬件组装到AI交互的完整实践

嵌入式系统开发是连接物理世界与数字世界的核心技术,其核心原理在于通过微控制器直接操作硬件外设,实现感知、决策与执行。这项技术的核心价值在于为物联网、智能硬件和机器人等领域提供了低功耗、高可靠性的解决方案。在机器人应用场景中,嵌入式平台常作为主控大脑,驱动舵机、传感器并处理交互逻辑。本文聚焦的Stack-chan项目,正是这一理念的生动实践:它采用流行的ESP32微控制器,并创新性地通过Moddable运行时支持使用JavaScript进行嵌入式开发,极大地降低了机器人编程的门槛。开发者可以基于此平台,轻松实

weixin_28729173的博客 436

python subprocess popen获取进程状态,如何从subprocess.Popen获取退出代码?

使用下面的代码,p.returncode始终为None.根据Popen.returncode documentation,这意味着该过程尚未完成.为什么我没有获得退出代码?import osimport sysimport subprocesscmd = ['echo','hello']p = subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=s...

weixin_29440125的博客 1585

基于PLC1200与CB1241的RS485从站Modbus Rtu通信实战指南

本文提供了一份详细的西门子S7-1200 PLC与CB1241 RS485通讯板实现Modbus RTU从站通信的实战指南。内容涵盖从硬件接线、博途软件组态、关键参数设置到程序调试与测试的全过程,重点解析了Modbus_Slave指令配置与数据块映射,帮助工程师快速掌握工业自动化系统中的数据采集与设备接入技术。

Apple的专栏 794

±10V ADC 输入电路的高共模差分输入电压

这篇文章分析了±10V ADC输入电路的设计需求与挑战,重点讨论了高共模差分输入电压的处理方案。文章首先明确了设计目标,即安全转换±10V差分信号并保持信号完整性,同时克服高共模电压、阻抗匹配和噪声优化等难点。随后详细比较了仪表放大器和差分放大器的性能特点,并提出了器件选型理论。在信号链架构部分,文章通过公式推导阐述了增益设置、共模抑制设计和输入阻抗匹配等关键技术。此外,还建立了噪声源模型,提出了噪声优化措施。最后,文章总结了设计验证方法,并扩展了在工业保护和生物电信号采集等场景的应用。该设计强调根据具体应

泛红尘的博客 1959

python类库 进程_python类库31[进程subprocess]

subprocess.Popen用来创建子进程。1)Popen启动新的进程与父进程并行执行,默认父进程不等待新进程结束。defTestPopen():importsubprocessp=subprocess.Popen("dir",shell=True)foriinrange(250):print("otherthings")2)p.wait函数使得父进程等待新创建的进程运行结束,然后再继续父...

weixin_36193690的博客 143

【GlobalMapper精品教程】006:Excel表格(.xls)或文本(.txt .csv)坐标文件生成矢量点

原始的坐标数据如下图所示,其中坐标为Lat经度,LNG纬度,均为十进制度的形式,一般软件都支持十进制度的格式,如果不支持,你可以尝试使用度分秒的形式,图中的DDMMSS-LAT为纬度,DDMMSS-LNG为经度。打开globalmapper软件,点击【打开数据文件】,选择坐标数据文件(案例中的数据位配套实验数据包中的data006.rar)气象台站分布点坐标.xls。选择坐标系:本案例数据采用的是经纬度,因此选择Geographic(Latitude/Longitude),基准选择WGS84,点击确定。

智慧空间实验室 2569

python类库31[进程subprocess与管道pipe]

  修改自: 原文 : Working with Python subprocess - Shells, Processes, Streams, Pipes, Redirects and More 地址 : http://jimmyg.org/blog/2009/working-with-python-subprocess.html   一 程序的stdin,stdout,stderr+...

weixin_34355559的博客 882

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

efm32 入门.pdf

本PDF共计22页,介绍的是操作驱动API,下载与否自己斟酌。

python subprocess pipe_python类库31[进程subprocess与管道pipe]

修改自:原文 : Working with Python subprocess - Shells, Processes, Streams, Pipes, Redirects and More一 程序的stdin,stdout,stderr+redirect+pipe程序的stdin,stdout,stderr:通常地一个应用程序默认地连接有3个io流,分别为stdin标准输入流,stdout标准输...

weixin_39930276的博客 134

深度学习工具包 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用法实例详解

一、简介 subprocess最早在2.4版本引入。用来生成子进程,并可以通过管道连接他们的输入/输出/错误,以及获得他们的返回值。 subprocess用来替换多个旧模块和函数: os.system os.spawn* os.popen* popen2.* commands.* 运行python的时候,我们都是在创建并运行一个进程,linux中一个进程可以fork一个子进程,并让这...

菲宇运维 7341

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

Python subprocess模块

https://www.pynote.net/archives/490 https://www.pynote.net/archives/2088 https://www.pynote.net/archives/1757 https://www.pynote.net/archives/1775 目录介绍引入subprocess模块subprocess.run() 函数的使用subprocess.Popen()函数的使用用subprocess启动后台进程关于subprocess子进程的communicate.

岁月的博客 1878

Python的subprocess模块

目录 一、简介 二、旧有模块的使用 1.os.system() 2. os.popen() 三、subprocess模块 1、subprocess.run() 2、subprocess.call() 3、subprocess.check_call() 4、subprocess.getstatusoutput() 5、subprocess.getoutput() ...

txwsmsm7023_的博客 865

python subprocess_Python subprocess模块功能与常见用法实例详解

本文实例讲述了Python subprocess模块功能与常见用法。分享给大家供大家参考,具体如下:一、简介subprocess最早在2.4版本引入。用来生成子进程,并可以通过管道连接他们的输入/输出/错误,以及获得他们的返回值。subprocess用来替换多个旧模块和函数:os.systemos.spawn*os.popen*popen2.*commands.*运行python的时候,我们都是在...

weixin_39575565的博客 450

python执行cmd subprocess持续_如何在python的程序中调用subprocess?

0. 结论简单的结论:subprocess.Popen永远要考虑将参数close_fds设置为True。通用的结论:fork进程时要考虑到子进程会共享父进程的所有已打开文件,在某些场景下尤其需要考虑到这可能会造成资源未及时释放的问题。1. 问题背景偶尔会有流程超时问题出现,发现现网的母机上存在mount.ntfs-3g或qemu-nbd进程被Compute通过subprocess.Popen(类似...

weixin_39580564的博客 459
上一篇: Zookeeper分布式安装手册
下一篇: Python tips: 什么是*args和**kwargs?
JasonChou0913
博客等级 码龄12年 1粉丝 0原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值