我正在编写一段代码,以便它能够处理来自fabric.local的错误,但是有些代码总是会因为错误而中止,并且永远不会进入except块。这是我的代码,希望能从你们那里得到一些想法
这个片段试图获取Vagrant端口,如果流浪者没有启动,就打开它。
def findsshport():
with settings(warn_only=True):
try:
print 'greping port'
return (local('vagrant ssh-config {} | grep Port'.format(env.vmId), capture=True))
except:
print 'vagrant not up'
with lcd('%s' % (buildfolder)):
local('vagrant up ext4')
return (local('vagrant ssh-config {} | grep Port'.format(env.vmId), capture=True))
env.user = 'root'
sshPort = findsshport()
env.hosts = ['127.0.0.1:' + sshPort.split()[1]]错误
[localhost] local: vagrant ssh-config 22921a7 | grep Port
Warning: local() encountered an error (return code 1) while executing 'vagrant ssh-config 22921a7 | grep Port'
Traceback (most recent call last):
File "/home/testing/local/lib/python2.7/site-packages/test123/fabriclogin.py", line 114, in sshlogin
env.hosts = ['127.0.0.1:' + sshPort.split()[1]]
AttributeError: 'NoneType' object has no attribute 'split'更新类似的问题和答案
Can I catch error codes when using Fabric to run() calls in a remote shell?
发布于 2018-07-30 03:56:04
好像这只是来自织物的警告。我的理解是,如果在ssh上遇到错误,它不会“转换”为Python错误,这就是异常块不能工作的原因。请提供错误跟踪以供进一步分析。
发布于 2018-07-30 23:43:15
Martin是对的,这是来自fabric.api.local的警告,python异常处理不会将其视为错误。相反,我看到的错误来自代码的另一部分,上面的代码片段返回了一些无效的内容。与try和except不同,if else与检查命令退出状态的return_code一起使用。
port = local('vagrant ssh-config {} | grep Port'.format(env.vmId), capture=True)
if port.return_code == 0:
return port
else:
with lcd('%s' % (buildfolder)):
local('vagrant up {}'.format(env.vmId), capture=True)
return (local('vagrant ssh-config {} | grep Port'.format(env.vmId), capture=True))发布于 2018-07-31 00:06:45
你的问题可能在这里。
with settings(warn_only=True)如果使用非零返回代码退出命令,则本地调用将引发异常。
def task_name():
with settings(warn_only=True):
try:
local("invalid_command")
except:
print("This will never print!")让我们来比较一下;
def task_name():
try:
local("invalid_command")
except:
print("This will print")https://stackoverflow.com/questions/51585739
复制相似问题