【问题标题】:Python cx_Freeze name __file__ is not definedPython cx_Freeze 名称 __file__ 未定义
【发布时间】:2014-03-23 03:50:52
【问题描述】:

我有一个 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)

setup.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],
    )

【问题讨论】:

  • 您不能在冻结的程序中使用__file__,因为该模块是从压缩文件中加载的。查看常见问题解答中的using data files

标签: python cx-freeze python-module setup.py self-reference


【解决方案1】:

来源:
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__))

使用 python 3.3.4 测试。在win32上

upd.:按照comment改了

【讨论】:

  • 基本上是我所做的
  • 这行得通,但对于任何可能没有意识到的阅读者来说,dir 是 Python 中的保留字。您可能应该命名
猜你喜欢
  • 2023-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-18
  • 2016-05-16
  • 2013-01-26
  • 2021-03-18
相关资源
最近更新 更多