Programming

다른 파일에서 사용할 외부 Python 코드를 포함시키는 방법은 무엇입니까?

procodes 2020. 7. 23. 20:38
반응형

다른 파일에서 사용할 외부 Python 코드를 포함시키는 방법은 무엇입니까?


파일에 메소드 모음이있는 경우 해당 파일을 다른 파일에 포함시키는 방법이 있습니까?하지만 접두사 (예 : 파일 접두사)없이 파일을 호출합니까?

그래서 내가 가지고 있다면 :

[Math.py]
def Calculate ( num )

이걸 어떻게 이렇게 부르죠 :

[Tool.py]
using Math.py

for i in range ( 5 ) :
    Calculate ( i )

다른 파일을 다음과 같은 모듈로 가져와야합니다.

import Math

Calculate함수에 모듈 이름 을 접두어로 사용하지 않으려면 다음을 수행하십시오.

from Math import Calculate

모듈의 모든 멤버를 가져 오려면 다음을 수행하십시오.

from Math import *

편집 : 다음은 이 주제에 대해 좀 더 자세히 설명하는 Dive Into Python 의 좋은 장 입니다 .


"include"명령을 작성하십시오.

import os

def include(filename):
    if os.path.exists(filename): 
        execfile(filename)


include('myfile.py')

@Deleet :

@bfieck 설명은 python 2 및 3 호환성을 위해 정확합니다.

파이썬 2와 3 : 대안 1

from past.builtins import execfile

execfile('myfile.py')

파이썬 2와 3 : 대안 2

exec(compile(open('myfile.py').read()))

사용하는 경우 :

import Math

그러면 Math 함수를 사용할 수 있지만 Math.Calculate를 수행해야하므로 원하지 않는 것입니다.

접두사없이 모듈의 함수를 가져 오려면 다음과 같이 명시 적으로 이름을 지정해야합니다.

from Math import Calculate, Add, Subtract

이제 이름만으로 계산, 더하기 및 빼기를 참조 할 수 있습니다. Math에서 모든 함수를 가져 오려면 다음을 수행하십시오.

from Math import *

그러나 내용이 확실치 않은 모듈로이 작업을 수행 할 때는 매우주의해야합니다. 동일한 기능 이름에 대한 정의가 포함 된 두 개의 모듈을 가져 오면 한 기능이 다른 기능을 덮어 쓰고 더 현명한 기능은 사용하지 않습니다.


python inspect 모듈이 매우 유용하다는 것을 알았습니다.

예를 들어 teststuff.py

import inspect

def dostuff():
    return __name__

DOSTUFF_SOURCE = inspect.getsource(dostuff)

if __name__ == "__main__":

    dostuff()

그리고 다른 스크립트 나 파이썬 콘솔에서

import teststuff

exec(DOSTUFF_SOURCE)

dostuff()

And now dostuff should be in the local scope and dostuff() will return the console or scripts _name_ whereas executing test.dostuff() will return the python modules name.

참고URL : https://stackoverflow.com/questions/714881/how-to-include-external-python-code-to-use-in-other-files

반응형