Dom*_*nik 1 python linux remote-access fabric
我正在使用 python Fabric 中的 run 命令远程执行脚本。
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))
Run Code Online (Sandbox Code Playgroud)
我的 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)
Run Code Online (Sandbox Code Playgroud)
当我执行 run 命令时,有没有办法查看我的函数中返回了哪个值,1 还是 0?
谢谢你!
stdout根据 Fabric 2.x 文档,默认情况下会捕获结果并在stderr结果的属性下提供: http://docs.fabfile.org/en/2.0/getting-started.html#run-commands-via-连接并运行
r = C.run('python3 ~/script.py')
print(r.stdout)
Run Code Online (Sandbox Code Playgroud)
该run命令返回一个Result对象,该对象具有以下属性(除其他外):
所以你需要检查exited/return_code属性。
但是,您的脚本不会随着函数的返回代码而退出。为此,您需要sys.exit使用该值,因此将 download_file 更改为:
sys.exit(download_file(url))
Run Code Online (Sandbox Code Playgroud)
将为您提供 download_file 函数的返回代码。您需要import sys在脚本上进行操作以确保该sys模块可用。
当程序因非零退出代码而失败时,UnexpectedExit将引发异常。为了在这种情况下获取退出代码,您可以 (a) 捕获异常,或 (b) 将参数传递给warn=True运行命令,因此运行命令如下所示:
r = C.run('python3 ~/script.py', warn=True)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5361 次 |
| 最近记录: |