이 파이썬 코드가 가져 오기/컴파일에 매달려 있지만 쉘에서 작동하는 이유는 무엇입니까?

StackOverflow https://stackoverflow.com/questions/1013064

문제

Python을 사용하여 파일을 SFTP로 사용하려고 노력하고 있으며 코드는 대화식 쉘에서 훌륭하게 작동합니다. 심지어 한 번에 붙여 넣습니다.

파일을 가져 오려면 (컴파일하기 위해) 코드는 예외 나 명백한 오류없이 매달려 있습니다.

코드를 컴파일 할 코드를 얻거나 다른 방법으로 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()

도움이 되었습니까?

해결책 3

이상 함을 제외하고, 나는 단지 가져 오기를 사용하여 코드를 컴파일했습니다. 스크립트를 함수로 바꾸는 것은 이러한 종류의 응용 프로그램에 대한 불필요한 합병증처럼 보입니다.

컴파일 및 찾은 대체 수단을 검색했습니다.

import py_compile
py_compile.compile("ProblemDemo.py")

이것은 의도 한대로 작동하는 PYC 파일을 생성했습니다. 따라서 배운 교훈은 가져 오기가 파이썬 스크립트를 컴파일하는 강력한 방법이 아니라는 것입니다.

다른 팁

수입 시간에 이런 종류의 코드를 실행하는 것이 나쁜 생각입니다. 왜냐하면 그것이 왜 매달린 지 잘 모르겠지만, 가져 오기 메커니즘이 Paramiko와 심하게 상호 작용하는 이상한 일을 할 수 있습니다 (스레드 관련 문제는 아마도?). 어쨌든 일반적인 솔루션은 기능을 함수로 구현하는 것입니다.

def my_expensive_function(args):
    pass

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

이런 식으로 모듈을 가져 오는 것만으로도 아무것도 수행하지 않지만 스크립트를 실행하면 명령 줄에서 주어진 인수로 기능이 실행됩니다.

이것은 직접적인 이유가 아니지만 거의 당신은 거의하지 않습니다 가져 오기에 "기능성"을 실행하고 싶습니다. 일반적으로 a를 정의해야합니다 수업 또는 기능 그런 다음 이렇게 부릅니다.

import mymodule
mymodule.run()

가져 오기에서 실행되는 "글로벌"코드는 일반적으로 가져 오기, 가변 정의, 기능 및 클래스 정의 등으로 제한되어야합니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top