Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I know the path of the running script in Python?

Tags:

python

path

My script.py creates a temporary file using a relative path.

When running it as:

python script.py

it works as expected.

But it doesn't work when you run it like:

python /path/to/script.py

The problem is that I don't know which path it will be running in. How can I get the absolute path to the script folder (the "/path/to") so the temporary file can be created in the same directory as the script?

What about the following?

os.path.abspath(os.path.dirname(__file__))
like image 266
Juanjo Conti Avatar asked Dec 03 '22 06:12

Juanjo Conti


1 Answers

Per the great Dive Into Python:

import sys, os

print 'sys.argv[0] =', sys.argv[0]             1
pathname = os.path.dirname(sys.argv[0])        2
print 'path =', pathname
print 'full path =', os.path.abspath(pathname)
like image 172
Jonathan Feinberg Avatar answered Dec 06 '22 10:12

Jonathan Feinberg