How to run a Python file not in directory from another Python file?

前端 未结 3 918
予麋鹿
予麋鹿 2020-12-11 05:09

Let\'s say I have a file foo.py, and within the file I want to execute a file bar.py. But, bar.py isn\'t in the same directory as foo.py, it\'s in a subdirectory call baz. W

3条回答
  •  死守一世寂寞
    2020-12-11 05:23

    Question implies that you want to run these as scripts, so yes: you could use execfile in 2.X or subprocess (call the interpreter and pass the script as an argument). You just need to provide absolute paths to the files.

    # Python 2.X only!
    execfile ('c:/python/scripts/foo/baz/baz.py')
    

    Doing it that literally is brittle, of course. If baz is always a subirectory of foo you could derive it from foo's file:

    baz_dir = os.path.join(os.path.dirname(__file__), "baz")
    baz_file = os.path.join(baz_dir, "baz.py")
    execfile(baz_file)
    

    If both files are in locations that can be seen by your python -- ie, the folders are in sys.path or have been added to the search path using site you can import baz from foo and call it's functions directly. If you need to actually act on information from baz, instead of just triggering an action, this is a better way to go. As long as there is an init.py in each folder You could just do

    import baz
    baz.do_a_function_defined_in_baz() 
    

提交回复
热议问题