os.path.dirname(sys.argv[0]) always returns nothing

John Gordon gordon at panix.com
Mon Aug 1 13:58:27 EDT 2011


In <9797b629-3fba-4b90-920f-e426683599e1 at a12g2000vbf.googlegroups.com> happykid <psyking841 at gmail.com> writes:

> I want to use this function to get the directory path of the running
> script, but it always returns empty string. Can anyone help me solve
> this? Thank you.

What is the value of sys.argv[0]?  You're supposed to pass a full
pathname to os.path.dirname, like so:

>>> import os
>>> os.path.dirname('/a/b/c/d/e.txt')
'/a/b/c/d'
>>>

If sys.argv[0] is just the program name, then it doesn't have a path,
which is why you get no results from os.path.dirname:

>>> import os
>>> os.path.dirname('foo.py')
''
>>>

Are you trying to obtain the full pathname of the program?  That's an
entirely different question.

-- 
John Gordon                   A is for Amy, who fell down the stairs
gordon at panix.com              B is for Basil, assaulted by bears
                                -- Edward Gorey, "The Gashlycrumb Tinies"




More information about the Python-list mailing list