IT

다른 스크립트에서 스크립트를 호출하는 가장 좋은 방법은 무엇입니까?

lottoking 2020. 3. 26. 08:30
반응형

다른 스크립트에서 스크립트를 호출하는 가장 좋은 방법은 무엇입니까?


모듈에없는 test1.py라는 스크립트가 있습니다. 스크립트 자체가 실행될 때 실행할 코드 만 있습니다. 함수, 클래스, 메소드 등이 없습니다. 서비스로 실행되는 다른 스크립트가 있습니다. 서비스로 실행되는 스크립트에서 test1.py를 호출하고 싶습니다.

예를 들면 다음과 같습니다.

파일 test1.py

print "I am a test"
print "see! I do nothing productive."

파일 service.py

# Lots of stuff here
test1.py # do whatever is in test1.py

파일을 열고 내용을 읽고 기본적으로 평가하는 방법 중 하나를 알고 있습니다. 더 좋은 방법이 있다고 가정합니다. 아니면 적어도 그렇게 희망합니다.


이를 수행하는 일반적인 방법은 다음과 같습니다.

test1.py

def some_func():
    print 'in test 1, unproductive'

if __name__ == '__main__':
    # test1.py executed as script
    # do something
    some_func()

service.py

import test1

def service_func():
    print 'service func'

if __name__ == '__main__':
    # service.py executed as script
    # do something
    service_func()
    test1.some_func()

이것은 파이썬 2에서 사용할 수 있습니다

execfile("test2.py")

중요한 경우 네임 스페이스 처리에 대한 설명서참조하십시오 .

파이썬 3에서는 (@fantastory 덕분에)

exec(open("test2.py").read());

그러나 다른 접근 방식을 사용해야합니다. 당신의 아이디어 (내가 볼 수있는 것)는 매우 깨끗하게 보이지 않습니다.


또 다른 방법:

파일 test1.py :

print "test1.py"

파일 service.py :

import subprocess

subprocess.call("test1.py", shell=True)

이 방법의 장점은 모든 코드를 서브 루틴에 넣기 위해 기존 Python 스크립트를 편집 할 필요가 없다는 것입니다.

문서 : Python 2 , Python 3


test1.py가 service.py 내부에서 호출 될 때와 동일한 기능으로 실행 가능하게하려면 다음과 같이하십시오.

test1.py

def main():
    print "I am a test"
    print "see! I do nothing productive."

if __name__ == "__main__":
    main()

service.py

import test1
# lots of stuff here
test1.main() # do whatever is in test1.py

이러면 안됩니다. 대신 다음을 수행하십시오.

test1.py :

 def print_test():
      print "I am a test"
      print "see! I do nothing productive."

service.py

#near the top
from test1 import print_test
#lots of stuff here
print_test()

사용 import test11 사용을위한 -이 스크립트를 실행합니다. 나중에 호출하려면 스크립트를 가져온 모듈로 취급하고 reload(test1)메소드를 호출하십시오 .

reload(module)실행될 :

  • 파이썬 모듈의 코드가 다시 컴파일되고 모듈 수준 코드가 다시 실행 되어 모듈 사전의 이름에 바인딩되는 새로운 객체 집합을 정의합니다. 확장 모듈의 초기화 기능이 호출되지 않습니다

간단한 sys.modules조치로 적절한 조치를 호출 할 수 있습니다. 스크립트 이름을 문자열 ( 'test1') 로 계속 참조하려면 ' import ()' 내장을 사용하십시오.

import sys
if sys.modules.has_key['test1']:
    reload(sys.modules['test1'])
else:
    __import__('test1')

import os

os.system("python myOtherScript.py arg1 arg2 arg3")  

os를 사용하면 터미널로 직접 전화를 걸 수 있습니다. 더 구체적으로 만들고 싶다면 입력 문자열을 로컬 변수와 연결할 수 있습니다.

command = 'python myOtherScript.py ' + sys.argv[1] + ' ' + sys.argv[2]
os.system(command)

왜 test1을 가져 오지 않습니까? 모든 파이썬 스크립트는 모듈입니다. 더 좋은 방법은 test1.py에서 main / run, test1을 가져오고 test1.main ()을 실행하는 것입니다. 또는 test1.py를 하위 프로세스로 실행할 수 있습니다.


이것은 subprocess라이브러리 의 예입니다 .

import subprocess

python_version = '3'
path_to_run = './'
py_name = '__main__.py'

# args = [f"python{python_version}", f"{path_to_run}{py_name}"]  # Avaible in python3
args = ["python{}".format(python_version), "{}{}".format(path_to_run, py_name)]

res = subprocess.Popen(args, stdout=subprocess.PIPE)
output, error_ = res.communicate()

if not error_:
    print(output)
else:
    print(error_)

여러 인수를 지정 해야하는 경우에도 http://hplgit.github.io/primer.html/doc/pub/tech/._tech-solarized012.html 에서 하나의 파이썬 스크립트를 호출하는 쉬운 예제를 찾았습니다 .

import subprocess
cmd = 'python train_frcnn.py --input_weight_path model_frcnn.hdf5 -o simple -p take2.csv'
subprocess.call(cmd, shell=True)

참고 URL : https://stackoverflow.com/questions/1186789/what-is-the-best-way-to-call-a-script-from-another-script

반응형