source

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

bestscript 2023. 1. 15. 17:28

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

는 제은은라는 스크립트를 가지고 있습니다.test1.py모듈에는 없습니다.스크립트 자체가 실행될 때 실행해야 하는 코드가 있을 뿐입니다.수, 래, 클, 서, 서, 서, 서, 서, 서, 습, 습, 습, 습, 습.서비스로 실행되는 다른 스크립트가 있습니다.하고 test1.py서비스로 실행 중인 스크립트에서 가져옵니다.

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

파일:

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

파일:

# 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()

서비스.화이

import test1

def service_func():
    print 'service func'

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

이것은 Python 2에서 다음을 사용하여 가능합니다.

execfile("test2.py")

중요한 경우 네임스페이스의 취급에 대해서는, 메뉴얼을 참조해 주세요.

Python 3에서는 (@fantastory 덕분에)를 사용하여 가능합니다.

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

다만, 다른 어프로치를 사용하는 것을 검토해 주세요.당신의 생각은 (내가 봤을 때) 그다지 깨끗해 보이지 않습니다.

다른 방법:

파일 test1.py:

print "test1.py"

파일 서비스py:

import subprocess

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

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

문서:Python 2, Python 3

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.py를 service.py 내에서 호출했을 때와 같은 기능으로 실행 가능한 상태로 유지하려면 다음과 같은 작업을 수행합니다.

test1.py

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

if __name__ == "__main__":
    main()

서비스.화이

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

는 런피를 선호한다:

#!/usr/bin/env python
# coding: utf-8

import runpy

runpy.run_path(path_name='script-01.py')
runpy.run_path(path_name='script-02.py')
runpy.run_path(path_name='script-03.py')

이러면 안 돼대신 다음 작업을 수행합니다.

test1.py:

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

서비스.화이

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

처음 사용할 때 사용합니다. 스크립트가 실행됩니다.나중에 호출할 경우 스크립트를 Import된 모듈로 처리하고 메서드를 호출합니다.

reload(module)뭇매를 맞다

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

의 간단한 체크를 사용하여 적절한 액션을 호출할 수 있습니다.스크립트명을 계속 문자열로 참조한다('test1'import()를 사용합니다.

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

언급했듯이, ★★★★★★★★★★★★★★★★★★★★★★★★★★★★.runpy는 현재 스크립트에서 다른 스크립트 또는 모듈을 실행하는 좋은 방법입니다.

덧붙여서, 트레이서나 디버거가 이것을 실시하는 것은 매우 일반적인 일이며, 그러한 상황에서는, 파일을 직접 Import 하거나, 서브 프로세스로 파일을 실행하거나 하는 방법은 통상은 동작하지 않습니다.

해서 사용할 가 있습니다.exec코드를 실행합니다. 것을 .run_globalsImport를 가져오다.를 참조해 주세요.runpy._run_code세한것 、 을을해해요요 。

왜 그냥 test1을 Import하지 않는 거죠?모든 python 스크립트는 모듈입니다.더 나은 방법은 예를 들어 test1.py에서 main/run, test1 Import 및 test1.main 실행 등의 함수를 사용하는 것입니다.또는 하위 프로세스로 test1.py을 실행할 수도 있습니다.

이 과정은 다소 비정통적이지만 모든 Python 버전에서 작동합니다.

'if' 조건 내에서 'recommend.py'이라는 이름의 스크립트를 실행하고 다음 명령을 사용한다고 가정합니다.

if condition:
       import recommend

기술은 다르지만 효과가 있습니다!

이것을 python 스크립트에 추가합니다.

import os
os.system("exec /path/to/another/script")

이 명령어는 셸에 입력된 것처럼 실행됩니다.

는 '하다'의 입니다.subprocess★★★★★★★★★★★★★★★★★★:

import subprocess

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

# args = [f"python{python_version}", f"{path_to_run}{py_name}"]  # works 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_)

runpy표준 도서관이 가장 편리합니다. 왜일까요?에러가 발생한 경우를 고려해야 합니다.test1.py및 ""를 사용하여runpy은 '어디서든'에서 수 .service.py향후 를 위해 를 기록하기 위해)와 개체 유형에 다름): 시. 트레이스백텍스트(향후 조사를 위해 로그파일에 에러를 기입하기 위해서)와 에러 오브젝트(에러 처리에 의해서 그 타입에 의해서 다릅니다).subprocess object이 object from object object from from object from from from from object from from from from from test1.py로로 합니다.service.py 출력만 , 「」를 참조해 주세요."import.py a module"하여 "test1.py" "Import"는 다음과 같습니다.runpy코드를 랩할 필요가 없기 때문에 더 좋습니다.test1.pydef main():★★★★★★ 。

코드 입니다.traceback마지막 오류 텍스트를 캐치하는 모듈:

import traceback
import runpy #https://www.tutorialspoint.com/locating-and-executing-python-modules-runpy

from datetime import datetime


try:
    runpy.run_path("./E4P_PPP_2.py")
except Exception as e:
    print("Error occurred during execution at " + str(datetime.now().date()) + " {}".format(datetime.now().time()))
    print(traceback.format_exc())
    print(e)

하위 프로세스를 사용하여 수행하는 예제입니다.

from subprocess import run

import sys

run([sys.executable, 'fullpathofyourfile.py'])

위의 예에 따르면 이것이 최선의 방법입니다.

# test1.py

def foo():
    print("hellow")
# test2.py
from test1 import foo # might be different if in different folder.
foo()

하지만 제목에 따르면os.startfile("path")작고 효과적이기 때문에 가장 좋은 방법입니다.이렇게 하면 지정된 파일이 실행됩니다.나의 python 버전은 3.x+입니다.

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