我的 Python 脚本的用户说他们收到以下错误:
Traceback (most recent call last):
File "MCManager.py", line 7, in <module>
os.chdir(os.path.dirname(__file__))
OSError: [Errno 2] No such file or directory: ''
脚本所在的目录怎么可能不存在?是兼容性问题吗?我使用与出现错误的操作系统和版本相同的操作系统和版本,并且无法复制它。
我的 Python 脚本的用户说他们收到以下错误:
Traceback (most recent call last):
File "MCManager.py", line 7, in <module>
os.chdir(os.path.dirname(__file__))
OSError: [Errno 2] No such file or directory: ''
脚本所在的目录怎么可能不存在?是兼容性问题吗?我使用与出现错误的操作系统和版本相同的操作系统和版本,并且无法复制它。
当从同一目录执行脚本时,它会在 Python 2 中发生,例如
$ echo "print __file__" > /tmp/spam.py
$ python /tmp/spam.py
/tmp/spam.py
$ cd /tmp
$ python spam.py
spam.py
一种解决方案是os.path.abspath(__file__)在代码中使用,以便您始终可以在以下所有三种使用情况下解析脚本目录:
$ cat /tmp/spam.py
import os
print os.path.dirname(os.path.abspath(__file__))
$ python /tmp/spam.py
/tmp
$ cd /tmp
$ python /tmp/spam.py
/tmp
$ python spam.py
/tmp