This question already has an answer here:
这个问题在这里已有答案:
- How do I get the path and name of the file that is currently executing? 24 answers
如何获取当前正在执行的文件的路径和名称? 24个答案
Duplicate of: In Python, how do I get the path and name of the file that is currently executing?
重复:在Python中,如何获取当前正在执行的文件的路径和名称?
I would like to find out the path to the currently executing script. I have tried os.getcwd() but that only returns the directory I ran the script from not the actual directory the script is stored.
我想找出当前正在执行的脚本的路径。我已经尝试过os.getcwd(),但只返回我运行脚本的目录,而不是脚本存储的实际目录。
2 个解决方案
#1
In Python, __file__
identifies the current Python file. Thus:
在Python中,__ file__标识当前的Python文件。从而:
print "I'm inside Python file %s" % __file__
will print the current Python file. Note that this works in imported Python modules, as well as scripts.
将打印当前的Python文件。请注意,这适用于导入的Python模块以及脚本。
#2
How about using sys.path[0]
如何使用sys.path [0]
You can do something like
'print os.path.join(sys.path[0], sys.argv[0])'
你可以做'print os.path.join(sys.path [0],sys.argv [0])'之类的事情。
#1
In Python, __file__
identifies the current Python file. Thus:
在Python中,__ file__标识当前的Python文件。从而:
print "I'm inside Python file %s" % __file__
will print the current Python file. Note that this works in imported Python modules, as well as scripts.
将打印当前的Python文件。请注意,这适用于导入的Python模块以及脚本。
#2
How about using sys.path[0]
如何使用sys.path [0]
You can do something like
'print os.path.join(sys.path[0], sys.argv[0])'
你可以做'print os.path.join(sys.path [0],sys.argv [0])'之类的事情。