开发者

Help with filetype association!

I have the actual a开发者_JAVA百科ssociation part down, but when I open the file that is associated with my Python program, how do I get the filepath of the file opened?

I think it is something like sys.argv? But that just returns the path to the python program, not the associated file.


The contents of sys.argv are platform-dependent, as noted in sys.argv. I do know that sys.argv[0] is the full path on Windows only when you open .py files using the shell by double-clicking on it. Using the command line just results in the script name.

The os module provides platform-independent solutions. The full path to your script should always be available with the following code:

import os.path
import sys

print os.path.abspath(sys.argv[0])


The __file__ attribute of your module looks what you're looking for. E.g., save in foo.py:

$ cat foo.py
print 'Hello', __file__
$ python foo.py 
Hello foo.py

os.path.abspath will help you if you want the absolute rather than relative path, etc, etc.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜