Question

I have a python script which gets an image from the internet, downloads it, sets as desktop background and updates after on minute. The problem is most likely cx_Freeze not including the os module, as the same code with absolute paths works fine. My code also works perfectly, until it goes through freezing. It works before it is frozen when I load throught the console, run from IDLE or double-click on it. Whenever i run the frozen file I get the error (If i use setup.py or 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

My Code

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],
    )
Was it helpful?

Solution

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

Your old line:

dir = path.dirname(__file__)

Substitute this with the following lines to run your script both frozen or unfrozen:

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

Tested with python 3.3.4. on win32

upd.: changed in accordance with the comment

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top