1

I'm currently converting a shell script to python and I'm having a problem. The current script uses the results of the last ran command like so.

if [ $? -eq 0 ];
then
    testPassed=$TRUE
else
    testPassed=$FALSE
fi

I have the if statement converted over just not sure about the $? part. As I am new to python I'm wondering if there is a similar way to do this?

4

2 に答える 2

3

subprocessそのためのモジュールを調べる必要があります。check_call終了コードを調べる方法があります(これは1つの方法であり、他の方法もあります)。マニュアルに記載されているように:

引数を指定してコマンドを実行します。コマンドが完了するのを待ちます。戻りコードがゼロの場合は戻り、そうでない場合はCalledProcessErrorを発生させます。CalledProcessErrorオブジェクトは、returncode属性に戻りコードを持ちます

この例は次のとおりです。

import subprocess

command=["ls", "-l"]

try:
  exit_code=subprocess.check_call(command)
  # Do something for successful execution here
  print("Program run")
except subprocess.CalledProcessError as e:
  print "Program exited with exit code", e.returncode
  # Do something for error here

これには出力も含まれ、ファイルにリダイレクトするか、次のように抑制することができます。

import subprocess
import os

command=["ls", "-l"]

try:
  exit_code=subprocess.check_call(command, stdout=open(os.devnull, "w"))
  # Do something for successful execution here
  print("Program run")
except subprocess.CalledProcessError as e:
  print "Program exited with exit code", e.returncode
  # Do something for error here

ゼロ以外の終了コードを使用した呼び出しの例を次に示します。

import subprocess
import os

command=["grep", "mystring", "/home/cwgem/testdir/test.txt"]

try:
  exit_code=subprocess.check_call(command, stdout=open(os.devnull, "w"))
  # Do something for successful execution here
  print("Program run")
except subprocess.CalledProcessError as e:
  print "Program exited with exit code", e.returncode
  # Do something for error here

出力:

$ python process_exitcode_test.py
Program exited with exit code 1

これは、上記のように処理できる例外としてキャプチャされます。これは、アクセスが拒否された、ファイルが見つからないなどの例外を処理しないことに注意してください。自分で処理する必要があります。

于 2013-03-06T16:40:05.793 に答える
1

shモジュールを使用することをお勧めします。Pythonでのシェルスクリプトがはるかに快適になります。

import sh
try:
    output = sh.ls('/some/nen-existant/folder')
    testPassed = True
except ErrorReturnCode:
    testPassed = False
于 2013-03-06T18:20:18.770 に答える