How do I get the path and name of the file that is currently executing?

后端 未结 29 2335
你的背包
你的背包 2020-11-22 06:43

I have scripts calling other script files but I need to get the filepath of the file that is currently running within the process.

For example, let\'s say I have th

相关标签:
29条回答
  • 2020-11-22 07:05

    p1.py:

    execfile("p2.py")
    

    p2.py:

    import inspect, os
    print (inspect.getfile(inspect.currentframe()) # script filename (usually with path)
    print (os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))) # script directory
    
    0 讨论(0)
  • 2020-11-22 07:06
    import sys
    
    print sys.path[0]
    

    this would print the path of the currently executing script

    0 讨论(0)
  • 2020-11-22 07:07
    print(__file__)
    print(__import__("pathlib").Path(__file__).parent)
    
    0 讨论(0)
  • 2020-11-22 07:08

    Since Python 3 is fairly mainstream, I wanted to include a pathlib answer, as I believe that it is probably now a better tool for accessing file and path information.

    from pathlib import Path
    
    current_file: Path = Path(__file__).resolve()
    

    If you are seeking the directory of the current file, it is as easy as adding .parent to the Path() statement:

    current_path: Path = Path(__file__).parent.resolve()
    
    0 讨论(0)
  • 2020-11-22 07:10

    Simplest way is:

    in script_1.py:

    import subprocess
    subprocess.call(['python3',<path_to_script_2.py>])
    

    in script_2.py:

    sys.argv[0]
    

    P.S.: I've tried execfile, but since it reads script_2.py as a string, sys.argv[0] returned <string>.

    0 讨论(0)
  • 2020-11-22 07:12
    import os
    os.path.dirname(__file__) # relative directory path
    os.path.abspath(__file__) # absolute file path
    os.path.basename(__file__) # the file name only
    
    0 讨论(0)
提交回复
热议问题