使用Python在scp期间捕获异常

时间:2016-02-17 09:23:25

标签: python exception-handling

我正在使用os.system("echo y | pscp.exe -q -i key.ppk file.txt server_location"),效果很好。我希望能够在传输因某些原因失败时捕获异常。是否有可能实现这一目标?

2 个答案:

答案 0 :(得分:0)

os.system()返回值取决于操作系统。在POSIX上,可能在某些Windows上,这可以工作:

retval = os.system(command)
print "command return value is %d" % (retval >> 8)

没有异常处理,只有shell返回值。位移是因为有人认为在一个变量中返回多个东西是有用的(前8位是杀死命令的信号)。

您可能希望查看子进程模块而不是os.system():它为您提供了更多控制(如果您使用subprocess.check_call()subprocess.check_output(),则包含非零返回值的异常即使它不是很有用:你仍然需要检查shell返回值以查看问题是什么。)

答案 1 :(得分:0)

虽然以下内容可行,read about os.system() and os.wait() here

import os
import sys

# Saving os.system return_value
# See explanation for os.system(), os.wait() regarding the 2 different bytes received

ret_val = os.system( command )

# Exiting with ret_val, after shifting the lower irrelevant 8 bits
# (the lower 8 bits of os.wait() is the kill signal for the command )

sys.exit( ret_val >> 8 )