Python cx_Freeze名称__file__未定义

时间:2014-02-21 14:54:22

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

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

1 个答案:

答案 0 :(得分:22)

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

更改