Python cx_Freeze中,名称__file__未定义。

10

我有一个Python脚本,可以从互联网获取图片、下载并设置为桌面背景,并在一分钟后更新。问题很可能是cx_Freeze没有包含os模块,因为使用绝对路径的相同代码运行良好。我的代码在冻结之前也可以完美地工作,通过控制台加载、从IDLE运行或双击它都能正常运行。每当我运行冻结文件时,我都会收到错误提示(如果我使用setup.py或cxfreeze file.py):

C:\Python33\Scripts>C:\Python33\Scripts\dist\desktopchanger.exe
Traceback (most recent call last):
  File "C:\Python33\lib\site-packages\cx_Freeze\initscripts\Console3.py", line 2
7, in <module>
    exec(code, m.__dict__)
  File "C:\Python33\desktopchanger.pyw", line 7, in <module>
    dir = path.dirname(__file__)
NameError: name '__file__' is not defined

我的代码

import pythoncom
from urllib import request
from win32com.shell import shell, shellcon
from time import sleep
from os import path

dir = path.dirname(__file__) #get dierctory script is in
startpath = str(path.join(dir+'/bg/bg.jpg')) #add /bg/bg.jpg to path of script

pathtoimg=[]
for char in startpath:
    if char != "/":
        pathtoimg.append(char)  #replace / with \, necessary for setting bg
    else:
        pathtoimg.append("\\")

newpath = "".join(pathtoimg)

def get_image():
    f = open(newpath, 'wb') #open .....\bg\bg.jpg
    f.write(request.urlopen('http://blablabl.com/totale.jpg? i=0.387725243344903').read()) #get image from web and write over previous file
    f.close()

while 1:
    get_image()


#sets background below
    iad = pythoncom.CoCreateInstance(shell.CLSID_ActiveDesktop, None,
          pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IActiveDesktop)
    iad.SetWallpaper(newpath, 0)
    iad.ApplyChanges(shellcon.AD_APPLY_ALL)
    sleep(60)

安装配置文件.py

from cx_Freeze import setup, Executable

exe=Executable(
     script="desktop_changer_with_url2.py",
     base="Win32Gui",
     icon="icon.ico"
     )

includes = ["os","urllib","time","pythoncom","win32com.shell"]

setup(
    name = "Heindl Webcam als Desktop" , 
    version = "1",
    description = "eowjbadpoaäbaaplabipösdbjosdobsaboösac bjcaähpdaöbökabidsidsöds.", 
    executables = [exe],
    )

1
在冻结的程序中不能使用 __file__,因为该模块是从 zip 文件中加载的。请查看 FAQ 中 使用数据文件 的内容。 - Thomas K
1个回答

27

来源:
http://cx-freeze.readthedocs.org/en/latest/faq.html

您的旧代码:

dir = path.dirname(__file__)

请使用以下代码替换原始代码,以便在脚本冻结或未冻结时都能运行:

if getattr(sys, 'frozen', False):
    # frozen
    dir_ = os.path.dirname(sys.executable)
else:
    # unfrozen
    dir_ = os.path.dirname(os.path.realpath(__file__))

在win32上使用Python 3.3.4进行测试

更新:根据评论更改


基本上我所做的是: - Naib
这个可以运行,但是对于可能不知道的读者来说,dir 是 Python 中的保留字。你应该考虑更改变量名。 - Travis Mehlinger

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