ホームページ > バックエンド開発 > Python チュートリアル > サブプロセスモジュールの導入と使用

サブプロセスモジュールの導入と使用

零下一度
リリース: 2017-07-23 13:46:44
オリジナル
9662 人が閲覧しました

1. サブプロセスと一般的に使用されるカプセル化関数
Python を実行するとき、私たちは皆プロセスを作成して実行します。 Linux プロセスと同様に、プロセスは子プロセスをフォークし、その子プロセスに別のプログラムを実行させることができます。 Python では、標準ライブラリのサブプロセス パッケージを使用してサブプロセスをフォークし、外部プログラムを実行します。
サブプロセス パッケージには、サブプロセスを作成するためのいくつかの関数が定義されています。これらの関数はさまざまな方法でサブプロセスを作成するため、必要に応じていずれかを選択して使用できます。さらに、サブプロセスは、プロセス間でテキスト通信を使用するための標準ストリームとパイプを管理するためのいくつかのツールも提供します。

subprocess.call()
親プロセスは子プロセスの完了を待ちます
終了情報(リターンコード、Linuxの終了コードに相当)を返します

subprocess.check_call()
親プロセスは子プロセスが完了するのを待ちます
Return 0
終了情報を確認します。 returncode が 0 でない場合、エラー subprocess.CalledProcessError が発生します。このオブジェクトには returncode 属性が含まれており、これは try...excel...

subprocess.check_output() で確認できます。
親プロセスは子プロセスの完了を待ちます
子プロセスの出力を標準出力に返します 結果
終了情報を確認します リターンコードが 0 でない場合、エラー subprocess.CalledProcessError が発生します。属性と出力属性は、標準出力の出力結果です。

1. はじめに

サブプロセスはバージョン 2.4 で初めて導入されました。子プロセスを生成し、その入力/出力/エラーをパイプ経由で接続し、戻り値を取得するために使用されます。

サブプロセスは、複数の古いモジュールと関数を置き換えるために使用されます:

  • os.system

  • os.spawn*

  • os.popen*

  • Popen2 .*

  • commands.*

Linuxでは、プロセスを作成して実行し、子プロセスに別のプログラムを実行させることができます。 Python では、標準ライブラリのサブプロセス パッケージを使用してサブプロセスをフォークし、外部プログラムを実行します。 subprocess パッケージには、サブプロセスを作成するための関数がいくつか定義されています。これらの関数はさまざまな方法でサブプロセスを作成するため、必要に応じてそのうちの 1 つを選択できます。さらに、サブプロセスは、プロセス間でテキスト通信を使用するための標準ストリームとパイプを管理するためのいくつかのツールも提供します。

2. 古いモジュールの使用

1.os.system()

OSのコマンドを実行し、結果を画面に出力し、コマンドの実行ステータス(0:成功、 0以外: 失敗)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

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()メソッドを使用して読み出すことができます

rReeee
3.サブプロセスモジュール1.run()コマンドの 0 または 0 以外

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

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.check_call()

コマンドを実行し、結果とステータスを返します。通常は 0 です。実行エラーがある場合は例外が発生します。 be throw

1

2

3

4

5

6

7

8

9

10

11

12

13

14

>>> 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)

ログイン後にコピー

4. subprocess.getstatusoutput()

文字列形式のコマンドは、タプル形式の結果を返します。 2番目の要素はコマンドの実行結果です

1

2

3

4

5

6

7

8

9

10

11

>>> 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

ログイン後にコピー

6. subprocess.check_output()

コマンドを実行し、printingの代わりに実行結果を返します

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

>>> 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.Popen()

実際、subprocessで使用される上記のメソッドはすべてsubprocess.Popenのカプセル化です。このPopenメソッドを見てみましょう。

1, stdout

標準出力

1

2

3

4

5

6

7

#执行正确

>>> 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

標準誤差

1

2

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

&#39;/root&#39;

ログイン後にコピー

  

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

4、poll()

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

1

2

3

4

5

6

7

>>> 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()

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

1

2

3

4

5

6

7

8

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

>>> obj.wait()

 

 

# 中间会一直等待

 

 

0

ログイン後にコピー

  

6、terminate()

结束进程

1

2

3

4

5

6

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的程序的进程号

1

2

3

4

5

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 中国語 Web サイトの他の関連記事を参照してください。

関連ラベル:
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
関連するチュートリアル
人気のおすすめ
最新のコース
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート