Python学习笔记(三):进程与线程

本文详细介绍了Python中的进程和线程。针对进程,讲解了如何执行指令、获取输出和控制输入,还提到了进程间通信的潜在问题。对于线程,重点在于基础知识和并行处理数据,讨论了线程同步、死锁问题以及多线程在并行计算中的应用。
摘要由CSDN通过智能技术生成

一、进程(process)

在Python中,进程的主要模块为subprocess模块,此模块旨在代替老的os.system,os.spawn*,os.popen*,popen2,commands模块,进一步减少编程人员的工作量,实现import this中体现的宗旨。附上官方文档链接:https://docs.python.org/3/library/subprocess.html

多进程变成在Linux中相当于打开多个终端进行操作,即在不同终端中运行不同的命令,在Windows中相当于打开多个cmd(暂不论powershell) 。本文在Windows 10 cmd下进行介绍。

1、简单执行指令

先行介绍subprocess.Popen类的成员,这个类是最进程中重要的一个类,相当于进程的模板。其成员与下面将要介绍的subprocess.call()函数相同。
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为必填项,后面皆有默认值。其中stdin,stdout,stderr,shell等较为常用。

subprocess的最简单的方法为subprocess.call()函数,基本用法如下:
import subprocess
child = subprocess.call("ping cn.bing.com")

这样相当于在cmd中输入ping cn.bing.com命令,当然,官方更推荐使用args,即将命令写成多个单词组成的列表形式:
import subprocess
child = subprocess.call(["ping", "cn.bing.com"])

这两种输入运行结果相同(若网络连接正常)。

当然,在输入与系统相关命令时,需要将shell设为True,例如:
import subprocess
child = subprocess.call(["dir", "/a"], shell=True)

若不设定shell的值,则运行时会报错。
FileNotFoundError: [WinError 2] 系统找不到指定的文件。

这种最简单的call函数属于非同步(asynchronously)执行,即只有当call执行完之后,控制权才会返回主进程。这种方式会造成许多不便。因此,Python还有另外一种实现方式:同步执行(synchronously)。

同步执行利用的是subprocess.Popen类,这个类可以用来构造进程。Popen的方法如下:

Popen.poll()
Check if child process has terminated. Set and returnreturncode attribute.

Popen.wait(timeout=None)
Wait for child process to terminate. Set and return returncode attribute.

If the process does not terminate after timeout seconds, raise a TimeoutExpired exception. It is safe to catch this exception and retry the wait.

Note This will deadlock when using stdout=PIPE or stderr=PIPE and the child process generates enough output to a pipe such that it blocks waiting for the OS pipe buffer to accept more data. Use Popen.communicate() when using pipes to avoid that.
Note The function is implemented using a busy loop (non-blocking call and shortsleeps). Use theasyncio module for an asynchronous wait: see asyncio.create_subprocess_exec.
Changed in version 3.3: timeout was added.

Deprecated since version 3.4: Do not use the endtime parameter. It is was unintentionally exposed in 3.3 but was left undocumented as it was intended to be private for internal use. Use timeout instead.

Popen.communicate(input=None, timeout=None)
Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait forprocess to terminate. The optional input argument should be data to be sent to the child process, orNone, if no data should be sent to the child. If streams were opened in text mode,input must be a string. Otherwise, it must be bytes.

communicate() returns a tuple (stdout_data, stderr_data). The data will be strings if streams were opened in text mode; otherwise, bytes.

Note that if you want to send data to the process’s stdin, you need to create the Popen object with stdin=PIPE. Similarly, to get anything other than None in the result tuple, you need to give stdout=PIPE and/or stderr=PIPE too.

If the process does not terminate after timeout seconds, a TimeoutExpired exception will be raised. Catching this exception and retrying communication will
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值