Program Tip

Python에서 가져온 모듈의 main ()을 호출 할 수 있습니까?

programtip 2020. 11. 10. 22:11
반응형

Python에서 가져온 모듈의 main ()을 호출 할 수 있습니까?


파이썬 에는 몇 가지 함수를 정의하는 myModule.py 모듈몇 가지 명령 줄 인수를 사용 하는 main ()이 있습니다.

나는 보통 bash 스크립트에서 이것을 main ()이라고 부른다. 이제 모든 것을 작은 패키지 에 넣고 싶습니다 . 그래서 간단한 bash 스크립트를 Python 스크립트로 바꿔서 패키지에 넣을 수있을 것이라고 생각했습니다.

그래서, 내가 어떻게 실제로 않는 주 ()를 호출 myModule.py의 기능을 주 () 함수에서 MyFormerBashScript.py의? 저도 할 수 있습니까? 인수어떻게 전달 합니까?


그것은 단지 기능입니다. 그것을 가져 와서 호출하십시오.

import myModule

myModule.main()

인수를 구문 분석해야하는 경우 두 가지 옵션이 있습니다.

  • 에서 구문 분석하되 매개 변수로 main()전달합니다 sys.argv(아래의 모든 코드는 동일한 모듈에 있음 myModule).

    def main(args):
        # parse arguments using optparse or argparse or what have you
    
    if __name__ == '__main__':
        import sys
        main(sys.argv[1:])
    

    이제 myModule.main(['arg1', 'arg2', 'arg3'])다른 모듈에서 가져오고 호출 할 수 있습니다 .

  • main()이미합니다 (다시 모든 코드를 구문 분석하는 매개 변수 동의 myModule모듈) :

    def main(foo, bar, baz='spam'):
        # run with already parsed arguments
    
    if __name__ == '__main__':
        import sys
        # parse sys.argv[1:] using optparse or argparse or what have you
        main(foovalue, barvalue, **dictofoptions)
    

    myModule.main(foovalue, barvalue, baz='ham')다른 곳에서 가져오고 호출 하고 필요에 따라 파이썬 인수를 전달합니다.

여기서 트릭은 모듈이 스크립트로 사용되는시기를 감지하는 것입니다. 파이썬 파일을 메인 스크립트 ( python filename.py) 로 실행하면 어떤 import문도 사용 되지 않으므로 파이썬은 해당 모듈을 호출합니다 "__main__". 그러나 동일한 filename.py코드가 모듈 ( import filename) 로 취급되면 파이썬은 대신 모듈 이름으로이를 사용합니다. 두 경우 모두 변수 __name__가 설정되고 이에 대한 테스트를 통해 코드가 어떻게 실행되었는지 알 수 있습니다.


Martijen의 대답은 의미가 있지만 다른 사람들에게는 분명해 보일지 모르지만 알아 내기가 어려웠던 중요한 것이 누락되었습니다.

argparse를 사용하는 버전에서는 본문에이 줄이 있어야합니다.

args = parser.parse_args(args)

일반적으로 스크립트에서 argparse를 사용하는 경우

args = parser.parse_args()

parse_args는 명령 줄에서 인수를 찾습니다. 그러나이 경우 주 함수는 명령 줄 인수에 액세스 할 수 없으므로 인수가 무엇인지 argparse에 알려야합니다.

다음은 예입니다.

import argparse
import sys

def x(x_center, y_center):
    print "X center:", x_center
    print "Y center:", y_center

def main(args):
    parser = argparse.ArgumentParser(description="Do something.")
    parser.add_argument("-x", "--xcenter", type=float, default= 2, required=False)
    parser.add_argument("-y", "--ycenter", type=float, default= 4, required=False)
    args = parser.parse_args(args)
    x(args.xcenter, args.ycenter)

if __name__ == '__main__':
    main(sys.argv[1:])

이 mytest.py 이름을 지정했다고 가정하면 실행하려면 명령 줄에서 다음 중 하나를 수행 할 수 있습니다.

python ./mytest.py -x 8
python ./mytest.py -x 8 -y 2
python ./mytest.py 

각각 반환

X center: 8.0
Y center: 4

또는

X center: 8.0
Y center: 2.0

또는

X center: 2
Y center: 4

또는 다른 파이썬 스크립트에서 실행하려면 다음을 수행하십시오.

import mytest
mytest.main(["-x","7","-y","6"]) 

반환하는

X center: 7.0
Y center: 6.0

때에 따라 다르지. 기본 코드가 ifas로 보호되는 경우 :

if __name__ == '__main__':
    ...main code...

then no, you can't make Python execute that because you can't influence the automatic variable __name__.

But when all the code is in a function, then might be able to. Try

import myModule

myModule.main()

This works even when the module protects itself with a __all__.

from myModule import * might not make main visible to you, so you really need to import the module itself.


I had the same need using argparse too. The thing is parse_args function of an argparse.ArgumentParser object instance implicitly takes its arguments by default from sys.args. The work around, following Martijn line, consists of making that explicit, so you can change the arguments you pass to parse_args as desire.

def main(args):
    # some stuff
    parser = argparse.ArgumentParser()
    # some other stuff
    parsed_args = parser.parse_args(args)
    # more stuff with the args

if __name__ == '__main__':
    import sys
    main(sys.argv[1:])

The key point is passing args to parse_args function. Later, to use the main, you just do as Martijn tell.


The answer I was searching for was answered here: How to use python argparse with args other than sys.argv?

If main.py and parse_args() is written in this way, then the parsing can be done nicely

# main.py
import argparse
def parse_args():
    parser = argparse.ArgumentParser(description="")
    parser.add_argument('--input', default='my_input.txt')
    return parser

def main(args):
    print(args.input)

if __name__ == "__main__":
    parser = parse_args()
    args = parser.parse_args()
    main(args)

Then you can call main() and parse arguments with parser.parse_args(['--input', 'foobar.txt']) to it in another python script:

# temp.py
from main import main, parse_args
parser = parse_args()
args = parser.parse_args([]) # note the square bracket
# to overwrite default, use parser.parse_args(['--input', 'foobar.txt'])
print(args) # Namespace(input='my_input.txt')
main(args)

Assuming you are trying to pass the command line arguments as well.

import sys
import myModule


def main():
    # this will just pass all of the system arguments as is
    myModule.main(*sys.argv)

    # all the argv but the script name
    myModule.main(*sys.argv[1:])

참고URL : https://stackoverflow.com/questions/14500183/in-python-can-i-call-the-main-of-an-imported-module

반응형