【发布时间】: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