简体   繁体   English

__file__和os.path模块不能很好地播放吗?

[英]__file__ and os.path module not playing nicely?

import os
print __file__
print os.path.dirname(__file__)
os.chdir('/tmp')
print __file__  # unchanged, of course
print os.path.dirname(__file__)  # now broken

I have this issue above where dirname(__file__) can no longer be relied upon after os.chdir has been used in the script, after module loader has set __file__ . 我上面有这个问题,在模块加载程序设置__file__之后,在脚本中使用了os.chdir之后,就不再依赖dirname(__file__)

What is the usual mechanism for working around this, assuming you may not know where/when/how os.chdir may have been called previously? 解决此问题的常用机制是什么,假设您可能不知道以前在哪里/何时/如何调用过os.chdir

edit: i hope this second example can better clarify my issue 编辑:我希望第二个例子可以更好地阐明我的问题

import os
old_dir = os.getcwd()
print os.path.abspath(__file__)
os.chdir('/tmp')
print os.path.abspath(__file__)
os.chdir(old_dir)

the output is like this : 输出是这样的:

wim@wim-acer:~$ python --version
Python 2.7.1+
wim@wim-acer:~$ pwd
/home/wim
wim@wim-acer:~$ python /home/wim/spam.py
/home/wim/spam.py
/home/wim/spam.py
wim@wim-acer:~$ python ./spam.py
/home/wim/spam.py
/tmp/spam.py

The __file__ must exist in sys.path somewhere. __file__必须存在于sys.path

for dirname in sys.path:
   if os.path.exists( os.path.join(dirname,__file__) ):
       # The directory name for `__file__` was dirname

The last example has a relative path element in the __file__ name ( ./xxx.py ). 最后一个示例在__file__名称( ./xxx.py )中具有相对路径元素。 When abspath is called with that it is expanded to the current directory. 调用abspath时,它将被扩展到当前目录。

If you put this code in a module you won't have that issue. 如果将此代码放在模块中,则不会有此问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM