プラットフォーム: Unix
commands は、システムへコマンド文字列を渡して実行する os.popen() のラッパー関数を含んでいるモジュールです。 外部で実行したコマンドの結果や、その終了ステータスを扱います。
subprocess がプロセスを生成してその結果を取得するためのより強力な手段を提供しています。 subprocess モジュールを使う方が commands モジュールを使うより好ましいです。
警告
3.x において、 getstatus() および二つの隠し関数(mk2arg() と mkarg()) は削除されました。また、 getstatusoutput() と getoutput() は subprocess モジュールに移動されました。
commands モジュールは以下の関数を定義しています。
文字列 cmd を os.popen() を使いシェル上で実行し、 タプル (status, output) を返します。 実際には { cmd; } 2>&1 と実行されるため、標準出力とエラー出力が混合されます。 また、出力の最後の改行文字は取り除かれます。 コマンドの終了ステータスはC言語関数の wait() の規則に従って解釈することができます。
getstatusoutput() に似ていますが、終了ステータスは無視され、コマンドの出力のみを返します。
ls -ld file の出力を文字列で返します。 この関数は getoutput() を使い、引数内の バックスラッシュ記号「\」とドル記号「$」を適切にエスケープします。
バージョン 2.6 で撤廃: この関数は明らかでないですし役立たずです。名前も 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'
参考