Python name cx_Freeze __file__ undefined

I have a python script that receives an image from the Internet, downloads it, sets it as the desktop background and updates after a minute. Most likely, the cx_Freeze problem does not include the os module, since the same code with absolute paths works fine. My code also works fine until it goes through freezing. It works before it is frozen, when I load the console, start from IDLE or double-click on it. Whenever I run a frozen file, I get an 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], ) 
+6
source share
1 answer

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

Your old line:

 dir = path.dirname(__file__) 

Replace this with the following lines to run the script, both frozen and non-freezing:

 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 according to comment

+21
source

All Articles