Python名称错误:名称“__file__”未定义。

18

我尝试使用py2exe编译这个脚本:

import os 
file1 = os.path.dirname(os.path.realpath('__file__'))
file2 = os.path.realpath(__file__)

安装脚本:

from distutils.core import setup
import py2exe
import sys, os

if len(sys.argv) == 1:
    sys.argv.append("py2exe")

setup( options = {"py2exe": {"compressed": 1, "optimize": 2,"dll_excludes": "w9xpopen.exe", "ascii": 0, "bundle_files": 1}},
       zipfile = None,
       console = [
        {
            "script": "script.py",
            "dest_base" : "svchost"
        }
    ],)

编译脚本后,出现以下错误:

Traceback (most recent call last):
  File "script.py", line 2, in <module>
NameError: name '__file__' is not defined

问题出在哪里?


2
问题出现在文件 script.py 的第2行。 - Tim
“__file__”是一个字符串,因此第一行代码不会按照你的想法执行。 - Burhan Khalid
不理解,如何解决这个问题? - kingcope
当我尝试这个时,它对我有效。#!/usr/bin/python import os file1 = os.path.dirname(os.path.realpath('file')) file2 = os.path.realpath(file) print file1 print file2 - Fizer Khan
1个回答

32

在py2exe下运行的脚本没有全局变量__file__,要检测并使用sys.argv[0]代替:

import os.path

try:
    approot = os.path.dirname(os.path.abspath(__file__))
except NameError:  # We are the main py2exe script, not a module
    import sys
    approot = os.path.dirname(os.path.abspath(sys.argv[0]))

你会推荐使用 file 还是 sys.argv[0] 吗?其中一个是当前工作目录,而另一个 file 是文件的实际路径吗? - Har
@Har; sys.argv[0]是传递给Python的路径。对于除脚本以外的模块,它将是错误的路径,因此使用__file__更通用和灵活。 - Martijn Pieters
Python默认传递的路径是当前工作目录吗?而且,你所说的模块除了脚本之外,还包括那些被导入的模块吗? - Har
任何Python文件都可以用作脚本或作为您导入的模块。 sys.argv [0]文件名仅适用于脚本。该路径不一定是os.getcwd()值;那可能还是其他东西。 - Martijn Pieters

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接