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方法可以查看退出代码(这是一种方法,还有其他方法)。正如手册中提到的:

运行带参数的命令。等待命令完成。如果返回码为零,则返回,否则引发 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 中的 shell 脚本编写更加愉快:

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