【问题标题】:Python Fabric return value on remote run command远程运行命令上的 Python Fabric 返回值
【发布时间】:2018-07-18 07:34:33
【问题描述】:

我正在使用 python Fabric 中的运行命令远程执行脚本。

C = fabric.Connection('ip', user='user', connect_kwargs={"password": "password"})
try:
   r = C.run('python3 ~/script.py')
   if r:
        print('{} SUCCESS'.format(C.host))
        break
   else:
        print('{} ERROR'.format(C.host))
        break
except:
    print('{} ERROR'.format(C.host))

我的 script.py 是:

def download_file(url, filename):
    try:
        response = requests.get(url)
        # Open file and write the content
        with open(filename, 'wb') as file:
            # A chunk of 128 bytes
            for chunk in response:
                file.write(chunk)
        return 1
    except requests.exceptions.RequestException as e:
        return 0

download_file(url,filename)

当我执行运行命令时,有没有办法查看我的函数中返回的值是 1 还是 0?

谢谢!

【问题讨论】:

    标签: python linux remote-access fabric


    【解决方案1】:

    根据 Fabric 2.x 文档,默认情况下会在 stdoutstderr 属性下捕获结果并提供结果:http://docs.fabfile.org/en/2.0/getting-started.html#run-commands-via-connections-and-run

    r = C.run('python3 ~/script.py')
    print(r.stdout)
    

    【讨论】:

      【解决方案2】:

      run 命令返回一个Result 对象,该对象具有以下属性(以及其他属性):

      • stdout - 标准输出
      • stderr - 标准错误
      • exited - 程序的退出代码
      • ok - 退出 == 0
      • return_code - exited 的别名

      所以你需要检查exited/return_code 属性。

      但是,您的脚本不会以函数的返回码退出。为此,您需要使用该值 sys.exit,因此将 download_file 更改为:

      sys.exit(download_file(url))
      

      会从 download_file 函数中得到返回码。您需要在脚本上 import sys 以确保您有可用的 sys 模块。

      当程序以非零退出代码失败时,将引发UnexpectedExit 异常。为了在这种情况下获得退出代码,您可以 (a) 捕获异常,或 (b) 将参数 warn=True 传递给运行命令,因此运行命令如下所示:

      r = C.run('python3 ~/script.py', warn=True)
      

      【讨论】:

      • 感谢您的回答。但是,如果我执行sys.exit(download_file(url,filename)),然后执行run 命令,我会得到一个错误的命令退出代码。我应该解决这个问题吗?
      • 您需要将warn=True 传递给运行命令,以在命令失败的情况下禁用异常触发。我已经用这个细节更新了答案。
      猜你喜欢
      • 2012-11-10
      • 1970-01-01
      • 1970-01-01
      • 2016-03-10
      • 2014-04-25
      • 1970-01-01
      • 1970-01-01
      • 2015-10-22
      • 1970-01-01
      相关资源
      最近更新 更多