Getting the full path the script is currently running in [Python]
Let me explain to you by explaining the outputs of all the commands you mentioned by running them in Windows.
Nothing special here, just importing some modules. Importing numpy
to test the commands.
In [1]: import os
...: import sys
...: import numpy
This gives the current working directory in which your process/program is executing. (detailed tutorial here)
In [2]: os.getcwd()
Out[2]: 'C:\\Users\\<username>'
This tells which file the module is loaded from which file.
In [3]: numpy.__file__
Out[3]: 'C:\\Users\\<username>\\anaconda3\\lib\\site-packages\\numpy\\__init__.py'
The path of the loaded file for the module, it can be a relative path.
In [4]: os.path.dirname(numpy.__file__)
Out[4]: 'C:\\Users\\Punit Singh\\anaconda3\\lib\\site-packages\\numpy'
The actual path of the loaded file for the module. See the difference from previous in lib
and Lib
. The folder name actually starts from the capital letter.
In [5]: os.path.dirname(os.path.realpath(numpy.__file__))
Out[5]: 'C:\\Users\\Punit Singh\\anaconda3\\Lib\\site-packages\\numpy'
This is the absolute path, you'll see the difference when you'll run this in Linux. It starts with the root folder denoted by \
.
In [6]: os.path.dirname(os.path.abspath(numpy.__file__))
Out[6]: 'C:\\Users\\Punit Singh\\anaconda3\\lib\\site-packages\\numpy'
[7]
and [8]
respectively give the path and absolute path of the file which is currently executing, here sys.argv[0]
returns the file which is currently executing, since currently, I am running ipython, it is ipython.exe shown in [9]
. (detailed tutorial here)
In [7]: os.path.dirname(sys.argv[0])
Out[7]: 'C:\\Users\\<username>\\anaconda3\\Scripts'
In [8]: os.path.abspath(os.path.dirname(sys.argv[0]))
Out[8]: 'C:\\Users\\<username>\\anaconda3\\Scripts'
In [9]: sys.argv[0]
Out[9]: 'C:\\Users\\<username>\\anaconda3\\Scripts\\ipython'
This gives the absolute path of the executable binary for the Python interpreter (documentation here)
In [10]: sys.executable
Out[10]: 'C:\\Users\\Punit Singh\\anaconda3\\python.exe'
Now coming to your requirement, I understand that you need to access files where this ipython.exe
as shown in [9]
is located, so you can use commands mentioned in [7]
or [8]
.
How do I get the path of the current executed file in Python?
You can't directly determine the location of the main script being executed. After all, sometimes the script didn't come from a file at all. For example, it could come from the interactive interpreter or dynamically generated code stored only in memory.
However, you can reliably determine the location of a module, since modules are always loaded from a file. If you create a module with the following code and put it in the same directory as your main script, then the main script can import the module and use that to locate itself.
some_path/module_locator.py:
def we_are_frozen():
# All of the modules are built-in to the interpreter, e.g., by py2exe
return hasattr(sys, "frozen")
def module_path():
encoding = sys.getfilesystemencoding()
if we_are_frozen():
return os.path.dirname(unicode(sys.executable, encoding))
return os.path.dirname(unicode(__file__, encoding))
some_path/main.py:
import module_locator
my_path = module_locator.module_path()
If you have several main scripts in different directories, you may need more than one copy of module_locator.
Of course, if your main script is loaded by some other tool that doesn't let you import modules that are co-located with your script, then you're out of luck. In cases like that, the information you're after simply doesn't exist anywhere in your program. Your best bet would be to file a bug with the authors of the tool.
Find path to currently running file
__file__
is NOT what you are looking for. Don't use accidental side-effects
sys.argv[0]
is always the path to the script (if in fact a script has been invoked) -- see http://docs.python.org/library/sys.html#sys.argv
__file__
is the path of the currently executing file (script or module). This is accidentally the same as the script if it is accessed from the script! If you want to put useful things like locating resource files relative to the script location into a library, then you must use sys.argv[0]
.
Example:
C:\junk\so>type \junk\so\scriptpath\script1.py
import sys, os
print "script: sys.argv[0] is", repr(sys.argv[0])
print "script: __file__ is", repr(__file__)
print "script: cwd is", repr(os.getcwd())
import whereutils
whereutils.show_where()
C:\junk\so>type \python26\lib\site-packages\whereutils.py
import sys, os
def show_where():
print "show_where: sys.argv[0] is", repr(sys.argv[0])
print "show_where: __file__ is", repr(__file__)
print "show_where: cwd is", repr(os.getcwd())
C:\junk\so>\python26\python scriptpath\script1.py
script: sys.argv[0] is 'scriptpath\\script1.py'
script: __file__ is 'scriptpath\\script1.py'
script: cwd is 'C:\\junk\\so'
show_where: sys.argv[0] is 'scriptpath\\script1.py'
show_where: __file__ is 'C:\\python26\\lib\\site-packages\\whereutils.pyc'
show_where: cwd is 'C:\\junk\\so'
How can I find script's directory?
You need to call os.path.realpath
on __file__
, so that when __file__
is a filename without the path you still get the dir path:
import os
print(os.path.dirname(os.path.realpath(__file__)))
How do I get the path and name of the file that is currently executing?
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
How do i get the path of the python script i am running in for multiple people
import inspect, os
print inspect.getfile(inspect.currentframe()) # file name and path of script
print os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) # directory script is running in
See this answered question
How do I find directory of the Python running script from inside the script?
To get the directory that contains the module you are running:
import os
path = os.path.dirname(os.path.realpath(__file__))
Or if you want the directory from which the script was invoked:
import os
path = os.getcwd()
From the docs:
__file__
is the pathname of the file from which the module was loaded, if it was loaded from a file.
Depending on how the script is called, this may be a relative path from os.getcwd()
, so os.path.realpath(__file__)
will convert this to an absolute path (or do nothing is the __file__
is already an absolute path). os.path.dirname()
will then return the full directory by stripping off the filename.
Related Topics
How to Make Ball Bounce Off Wall with Pygame
How to Pass a List as a Command-Line Argument with Argparse
How to Do Parallel Programming in Python
How to Make an Immutable Object in Python
How to "Test" Nonetype in Python
Error: Command 'Gcc' Failed with Exit Status 1 While Installing Eventlet
Combine Several Images Horizontally with Python
Python Date String to Date Object
Running Selenium Webdriver with a Proxy in Python
Display Image as Grayscale Using Matplotlib
How to Print a String at a Fixed Width
Replace Values in List Using Python
Importing Variables from Another File
Does SQLalchemy Have an Equivalent of Django's Get_Or_Create
Executing Multi-Line Statements in the One-Line Command-Line