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
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
import sys
print sys.path[0]
this would print the path of the currently executing script
print(__file__)
print(__import__("pathlib").Path(__file__).parent)
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()
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>
.
import os
os.path.dirname(__file__) # relative directory path
os.path.abspath(__file__) # absolute file path
os.path.basename(__file__) # the file name only