python - 远程运行命令上的 Python Fabric 返回值
问题描述
我正在使用 python 结构中的运行命令远程执行脚本。
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?
谢谢!
解决方案
根据 Fabric 2.x 文档,默认情况下会在结果的stdout
和stderr
属性下捕获并提供结果:http ://docs.fabfile.org/en/2.0/getting-started.html#run-commands-via-连接并运行
r = C.run('python3 ~/script.py')
print(r.stdout)