Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the path of my python script?

Tags:

python

I am trying to get the path of my python script.

I know 'sys.argv[0] gives me the path and the name of my python script.

how can I just get the path?

I tried:

 print sys.argv[0]
    path = sys.argv[0].split("/")
    scriptpath = "".join(path[0:-1])

But it does not add back the path separator.

like image 513
michael Avatar asked Oct 17 '25 09:10

michael


2 Answers

Prefer to use __file__, like this:

os.path.dirname(os.path.realpath(__file__))

Note: using sys.argv[0] may not work if you call the script via another script from another directory.

like image 86
wim Avatar answered Oct 18 '25 23:10

wim


you're looking for os.path.dirname(), in case you might have a relative pathame, you need os.path.abspath() too

like image 37
SingleNegationElimination Avatar answered Oct 18 '25 23:10

SingleNegationElimination



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!