python calling a module that uses argparser

前端 未结 3 2008
傲寒
傲寒 2021-02-05 07:23

This is probably a silly question, but I have a python script that current takes in a bunch of arguements using argparser and I would like to load this script as a module in ano

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-05 07:51

    There may be a simpler and more pythonic way to do this, but here is one possibility using the subprocess module:

    Example:

    child_script.py

    import argparse
    
    parser = argparse.ArgumentParser()
    parser.add_argument("-n", "--name", help="your name")
    args = parser.parse_args()
    
    print("hello there {}").format(args.name)
    

    Then another Python script can call that script like so:

    calling_script.py:

    import subprocess
    
    # using Popen may suit better here depending on how you want to deal
    # with the output of the child_script.
    subprocess.call(["python", "child_script.py", "-n", "Donny"])
    

    Executing the above script would give the following output:

    "hello there Donny"
    

提交回复
热议问题