4

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.

1
  • change "".join(path[0:-1]) to "/".join(path[0:-1]) if you had to have that specific solution for whatever reason :) Commented Nov 21, 2012 at 23:19

4 Answers 4

8

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Unfortunately this one doesn't work as intended, if you use PyInstaller, because it is unpacked into a temporary folder which then is (correctly) returned as the path of the __file__. In this case dirname(realpath(sys.argv[0])) works fine.
3

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

Comments

1

Don't try string operations on paths, use the os.path module instead. E.g.:

scriptpath = os.path.dirname(sys.argv[0])

Comments

0

From another Stackoverflow thread

import sys, os

print 'sys.argv[0] =', sys.argv[0]             
pathname = os.path.dirname(sys.argv[0])        
print 'path =', pathname
print 'full path =', os.path.abspath(pathname)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.