PythonがShellスクリプトを呼び出す方法


1.osモジュールのpopenメソッドはos.popen()はfile readのオブジェクトを返し、read()を読み出す操作で実行された出力が表示されます.
>>> os.popen('date -u |wc')
<open file 'date -u |wc', mode 'r' at 0x7f9539eb34b0>
>>> os.popen('date -u |wc').read()
'      1       6      43
'

2.commandsモジュールを利用するこのモジュールには、プログラムが実行する戻り値をcommandsで直接読み取る非常に使いやすい方法がある.getstatusoutput()メソッドは、戻り値と出力を得ることができます.
>>> import commands
>>> commands.getstatusoutput('ls /bin/ls')
(0, '/bin/ls')
>>> commands.getstatusoutput('cat /bin/junk')
(256, 'cat: /bin/junk: No such file or directory')
>>> commands.getstatusoutput('/bin/junk')
(256, 'sh: /bin/junk: not found')
>>> commands.getoutput('ls /bin/ls')
'/bin/ls'
>>> commands.getstatus('/bin/ls')
'-rwxr-xr-x 1 root 13352 Oct 14 1994 /bin/ls'

3.subprocessモジュールsubprocessモジュールを使用して、他のプログラムを終了し、複数のプロセスを作成します.shellで他のプログラムを実行して出力を取得するには、check_を使用します.output()メソッド.コマンドとパラメータのリストを受け入れます.
>>> subprocess.check_output(["echo", "Hello World!"])
'Hello World!
' >>> ret = subprocess.check_output(['date','-u']) >>> ret '2016\xe5\xb9\xb4 05\xe6\x9c\x88 20\xe6\x97\xa5 \xe6\x98\x9f\xe6\x9c\x9f\xe4\xba\x94 09:48:44 UTC
'