Skip to main content
 首页 » 编程设计

python之为什么这个 python 代码在导入/编译时挂起但在 shell 中工作

2025年05月04日19thcjp

我正在尝试使用 python 来 sftp 文件,并且代码在交互式 shell 中运行良好——甚至可以一次性粘贴它。

当我尝试导入文件(只是为了编译它)时,代码挂起,没有异常或明显错误。

我如何获得要编译的代码,或者是否有人拥有通过其他方法完成 sftp 的工作代码?

此代码卡在 ssh.connect() 语句处:

""" ProblemDemo.py 
    Chopped down from the paramiko demo file. 
 
    This code works in the shell but hangs when I try to import it! 
""" 
from time           import sleep 
import os 
 
import paramiko 
 
 
sOutputFilename     = "redacted.htm"  #-- The payload file 
 
hostname    = "redacted.com" 
####-- WARNING!  Embedded passwords!  Remove ASAP. 
sUsername   = "redacted" 
sPassword   = "redacted" 
sTargetDir  = "redacted" 
 
#-- Get host key, if we know one. 
hostkeytype = None 
hostkey     = None 
host_keys   = {} 
try: 
    host_keys = paramiko.util.load_host_keys(os.path.expanduser('~/.ssh/known_hosts')) 
except IOError: 
    try: 
        # try ~/ssh/ too, because windows can't have a folder named ~/.ssh/ 
        host_keys = paramiko.util.load_host_keys(os.path.expanduser('~/ssh/known_hosts')) 
    except IOError: 
        print '*** Unable to open host keys file' 
        host_keys = {} 
 
if host_keys.has_key(hostname): 
    hostkeytype = host_keys[hostname].keys()[0] 
    hostkey     = host_keys[hostname][hostkeytype] 
    print 'Using host key of type %s' % hostkeytype 
 
 
ssh     = paramiko.Transport((hostname, 22)) 
 
ssh.connect(username=sUsername, password=sPassword, hostkey=hostkey) 
 
sftp    = paramiko.SFTPClient.from_transport(ssh) 
 
sftp.chdir (sTargetDir) 
 
sftp.put (sOutputFilename, sOutputFilename) 
 
ssh.close() 
 

请您参考如下方法:

在导入时执行这种代码确实是个坏主意,虽然我不确定它为什么会挂起 - 可能是导入机制做了一些奇怪的事情,与 paramiko 交互不良(可能是线程相关问题?)。无论如何,通常的解决方案是将功能实现为一个函数:

def my_expensive_function(args): 
    pass 
 
if __name__ == '__main__': 
    import sys 
    my_expensive_functions(sys.args) 

这样,仅仅导入模块不会做任何事情,但是运行脚本会在命令行执行带有给定参数的函数。