>  기사  >  백엔드 개발  >  하위 프로세스 모듈 소개 및 사용

하위 프로세스 모듈 소개 및 사용

零下一度
零下一度원래의
2017-07-23 13:46:449453검색

1. 하위 프로세스 및 일반적으로 사용되는 캡슐화 기능
파이썬을 실행할 때 우리는 모두 프로세스를 생성하고 실행합니다. Linux 프로세스와 마찬가지로 프로세스는 하위 프로세스를 분기하고 하위 프로세스가 다른 프로그램을 실행하도록 할 수 있습니다. Python에서는 표준 라이브러리의 하위 프로세스 패키지를 사용하여 하위 프로세스를 포크하고 외부 프로그램을 실행합니다.
하위 프로세스 패키지는 하위 프로세스를 생성하기 위한 여러 기능을 정의합니다. 이러한 함수는 다양한 방식으로 하위 프로세스를 생성하므로 필요에 따라 그 중 하나를 선택할 수 있습니다. 또한 하위 프로세스는 프로세스 간 텍스트 통신을 사용하기 위해 표준 스트림 및 파이프를 관리하는 몇 가지 도구도 제공합니다.

subprocess.call()
상위 프로세스는 하위 프로세스가 완료될 때까지 기다립니다.
종료 정보 반환(리턴코드, Linux 종료 코드와 동일)

subprocess.check_call()
상위 프로세스는 하위 프로세스가 완료될 때까지 기다립니다
Return 0
returncode가 0이 아니면 종료 정보를 확인하세요. subprocess.CalledProcessError 오류가 발생합니다. 객체에는 returncode 속성이 포함되어 있으며, 이는 try...Exception...

subprocess.check_output()으로 확인할 수 있습니다.
상위 프로세스는 하위 프로세스가 완료될 때까지 기다립니다.
하위 프로세스의 출력을 표준 출력으로 반환합니다. 결과
종료 정보를 확인합니다. 반환 코드가 0이 아니면 오류 subprocess.CalledProcessError가 발생합니다. 속성과 출력 속성은 표준 출력의 출력 결과입니다. try...Exception...을 사용하여 확인할 수 있습니다.

1. 소개

하위 프로세스는 버전 2.4에서 처음 도입되었습니다. 하위 프로세스를 생성하고 파이프를 통해 입력/출력/오류를 연결하고 반환 값을 얻는 데 사용됩니다.

 하위 프로세스는 여러 개의 오래된 모듈과 기능을 대체하는 데 사용됩니다:

  • os.system

  • os.spawn*

  • os.popen*

  • popen2 .*

  • commands.*

Python을 실행할 때 프로세스를 생성하고 실행하면 프로세스가 하위 프로세스를 포크하여 다른 프로그램을 실행할 수 있습니다. Python에서는 표준 라이브러리의 하위 프로세스 패키지를 사용하여 하위 프로세스를 포크하고 외부 프로그램을 실행합니다. subprocess 패키지는 하위 프로세스를 생성하기 위한 여러 함수를 정의하므로 이러한 함수는 다양한 방식으로 하위 프로세스를 생성하므로 필요에 따라 그 중 하나를 선택할 수 있습니다. 또한 하위 프로세스는 프로세스 간 텍스트 통신을 사용하기 위해 표준 스트림 및 파이프를 관리하는 몇 가지 도구도 제공합니다.

2. 기존 모듈 사용

1.os.system()

운영 체제의 명령을 실행하고 결과를 화면에 출력하며 명령 실행 상태(0:성공, non-0: failure )

import os

>>> a = os.system("df -Th")
Filesystem     Type   Size  Used Avail Use% Mounted on
/dev/sda3      ext4   1.8T  436G  1.3T  26% /
tmpfs          tmpfs   16G     0   16G   0% /dev/shm
/dev/sda1      ext4   190M  118M   63M  66% /boot

>>> a
0         # 0 表示执行成功


# 执行错误的命令
>>> res = os.system("list")
sh: list: command not found
>>> res
32512       # 返回非 0 表示执行错误

 

2.os.popen()

운영 체제의 명령을 실행하고 그 결과를 메모리에 저장합니다. read() 메서드를 사용하여 읽을 수 있습니다

import os

>>> res = os.popen("ls -l")

# 将结果保存到内存中
>>> print res
<open file &#39;ls -l&#39;, mode &#39;r&#39; at 0x7f02d249c390>

# 用read()读取内容
>>> print res.read()
total 267508
-rw-r--r--  1 root root    260968 Jan 27  2016 AliIM.exe
-rw-------. 1 root root      1047 May 23  2016 anaconda-ks.cfg
-rw-r--r--  1 root root   9130958 Nov 18  2015 apache-tomcat-8.0.28.tar.gz
-rw-r--r--  1 root root         0 Oct 31  2016 badblocks.log
drwxr-xr-x  5 root root      4096 Jul 27  2016 certs-build
drwxr-xr-x  2 root root      4096 Jul  5 16:54 Desktop
-rw-r--r--  1 root root      2462 Apr 20 11:50 Face_24px.ico

 

3. subprocess 모듈

1.subprocess.run()

>>> import subprocess
# python 解析则传入命令的每个参数的列表
>>> subprocess.run(["df","-h"])
Filesystem            Size  Used Avail Use% Mounted on
/dev/mapper/VolGroup-LogVol00
                      289G   70G  204G  26% /
tmpfs                  64G     0   64G   0% /dev/shm
/dev/sda1             283M   27M  241M  11% /boot
CompletedProcess(args=[&#39;df&#39;, &#39;-h&#39;], returncode=0)

# 需要交给Linux shell自己解析,则:传入命令字符串,shell=True
>>> subprocess.run("df -h|grep /dev/sda1",shell=True)
/dev/sda1             283M   27M  241M  11% /boot
CompletedProcess(args=&#39;df -h|grep /dev/sda1&#39;, returncode=0)

 

2. 결과 및 실행 상태 0 또는 0이 아닌

>>> res = subprocess.call(["ls","-l"])
总用量 28
-rw-r--r--  1 root root     0 6月  16 10:28 1
drwxr-xr-x  2 root root  4096 6月  22 17:48 _1748
-rw-------. 1 root root  1264 4月  28 20:51 anaconda-ks.cfg
drwxr-xr-x  2 root root  4096 5月  25 14:45 monitor
-rw-r--r--  1 root root 13160 5月   9 13:36 npm-debug.log

# 命令执行状态
>>> res
0

 

3.subprocess.check_call()

명령을 실행하고 결과와 상태를 반환합니다. 일반적으로 실행 오류가 있는 경우 예외가 발생합니다. be throw

>>> subprocess.check_call(["ls","-l"])
总用量 28
-rw-r--r--  1 root root     0 6月  16 10:28 1
drwxr-xr-x  2 root root  4096 6月  22 17:48 _1748
-rw-------. 1 root root  1264 4月  28 20:51 anaconda-ks.cfg
drwxr-xr-x  2 root root  4096 5月  25 14:45 monitor
-rw-r--r--  1 root root 13160 5月   9 13:36 npm-debug.log
0

>>> subprocess.check_call(["lm","-l"])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python2.7/subprocess.py", line 537, in check_call
    retcode = call(*popenargs, **kwargs)
  File "/usr/lib64/python2.7/subprocess.py", line 524, in call
    return Popen(*popenargs, **kwargs).wait()
  File "/usr/lib64/python2.7/subprocess.py", line 711, in __init__
    errread, errwrite)
  File "/usr/lib64/python2.7/subprocess.py", line 1327, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory

 

4.subprocess.getstatusoutput()

문자 허용 문자열 형식의 명령은 결과를 튜플 형식으로 반환합니다. 두 번째 요소는 명령 실행 결과를 반환합니다. , subprocess.Popen()

사실 위의 subprocess 메서드는 모두 subprocess.Popen을 캡슐화한 것입니다. 이 Popen 메서드를 살펴보겠습니다.

1, stdout

표준 출력

#执行正确
>>> subprocess.getstatusoutput(&#39;pwd&#39;)
(0, &#39;/root&#39;)

#执行错误
>>> subprocess.getstatusoutput(&#39;pd&#39;)
(127, &#39;/bin/sh: pd: command not found&#39;)

 

2, stderr

표준 오류

>>> subprocess.getoutput(&#39;pwd&#39;)
&#39;/root&#39;

  

注意:上面的提到的标准输出都为啥都需要等于subprocess.PIPE,这个又是啥呢?原来这个是一个管道,这个需要画一个图来解释一下:

4、poll()

定时检查命令有没有执行完毕,执行完毕后返回执行结果的状态,没有执行完毕返回None

>>> res = subprocess.Popen("sleep 10;echo &#39;hello&#39;",shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
>>> print(res.poll())
None
>>> print(res.poll())
None
>>> print(res.poll())
0

  

5、wait()

等待命令执行完成,并且返回结果状态

>>> obj = subprocess.Popen("sleep 10;echo &#39;hello&#39;",shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
>>> obj.wait()


# 中间会一直等待


0

  

6、terminate()

结束进程

import subprocess

>>> res = subprocess.Popen("sleep 20;echo &#39;hello&#39;",shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
>>> res.terminate()  # 结束进程
>>> res.stdout.read() 
b&#39;&#39;

7、pid

获取当前执行子shell的程序的进程号

import subprocess

>>> res = subprocess.Popen("sleep 5;echo &#39;hello&#39;",shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
>>> res.pid  # 获取这个linux shell 的 进程号
2778

위 내용은 하위 프로세스 모듈 소개 및 사용의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.