how to execute a python script file with an argument from inside another python script file

前端 未结 5 1503
灰色年华
灰色年华 2020-12-01 14:05

my problem is that I want to execute a python file with an argument from inside another python file to get the returned values....

I don\'t know if I\'ve explained

5条回答
  •  盖世英雄少女心
    2020-12-01 14:49

    Another way that may be preferable to using os.system() would be to use the subprocess module which was invented to replace os.system() along with a couple of other slightly older modules. With the following program being the one you want to call with some master program:

    import argparse
    
    # Initialize argument parse object
    parser = argparse.ArgumentParser()
    
    # This would be an argument you could pass in from command line
    parser.add_argument('-o', action='store', dest='o', type=str, required=True,
                        default='hello world')
    
    # Parse the arguments
    inargs = parser.parse_args()
    arg_str = inargs.o 
    
    # print the command line string you passed (default is "hello world")
    print(arg_str)
    

    Using the above program with subproccess from a master program would would look like this:

    import subprocess
    
    # run your program and collect the string output
    cmd = "python your_program.py -o THIS STRING WILL PRINT"
    out_str = subprocess.check_output(cmd, shell=True)
    
    # See if it works.
    print(out_str)
    

    At the end of the day this will print "THIS STRING WILL PRINT", which is the one you passed into what I called the master program. subprocess has lots of options but it is worth using because if you use it write your programs will be system independent. See the documentation for subprocess, and argparse.

提交回复
热议问题