[英]cx_freeze module dependency
所以我的 python 腳本依賴於我創建的另一個模塊。 該模塊讀入一個文本文件。 當我從源代碼運行時,腳本、模塊和它讀取的文件通常位於同一目錄中,並且一切正常。
我是用cx_freeze編譯的,運行的時候,導入的模塊失敗了。 該模塊嘗試讀取該文件並說它找不到它,然后一切都停止了。
文本文件包含在 library.zip 和 build 文件夾中(可能是不必要的,但我認為它不會受到傷害)。 我決定在讀取文件之前打印模塊中的工作目錄以查看發生了什么,看起來工作目錄不是構建文件夾,而是我的用戶主目錄。
當然,文本文件不在我用戶的主目錄中。 我怎樣才能解決這個問題?
只是為了具體,這里有一個例子。 所有文件都在同一目錄中。
腳本.py:
import hello
你好.py
import os
print(os.getcwd())
f = open('hello.txt','r')
print(f.read())
f.close()
你好.txt
hello!
設置文件
import sys
import os
from cx_Freeze import setup, Executable
# Dependencies are automatically detected, but it might need fine tuning.
includes = ['hello.txt']
zip_inc = ['hello.txt']
build_exe_options = {"packages": ["os"], "include_files": includes, "zip_includes": zip_inc}
setup( name = "test",
version = "0.1",
description = "test",
options = {"build_exe": build_exe_options},
executables = [Executable("script.py")])
我用命令構建:
python setup.py build
然后我在構建目錄中運行名為 script 的文件。 如果重要的話,我在 Mac OS X 中。 輸出如下:
/Users/pianowow
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/cx_Freeze/initscripts/Console3.py", line 27, in <module>
exec(code, m.__dict__)
File "script.py", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/importlib/_bootstrap.py", line 1558, in _find_and_load
return _find_and_load_unlocked(name, import_)
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/importlib/_bootstrap.py", line 1525, in _find_and_load_unlocked
loader.load_module(name)
File "/Users/pianowow/Desktop/test/hello.py", line 3, in <module>
f = open('hello.txt','r')
FileNotFoundError: [Errno 2] No such file or directory: 'hello.txt'
我有一個更新文檔的拉取請求 - 這是關於使用數據文件的更新部分:
應用程序通常需要除代碼之外的數據文件,例如圖標。 使用安裝腳本,您可以在 build_exe 的 include_files 選項中列出數據文件或目錄。 它們將與可執行文件一起復制到構建目錄中。 然后要找到它們,請使用如下代碼:
def find_data_file(filename):
if getattr(sys, 'frozen', False):
# The application is frozen
datadir = os.path.dirname(sys.executable)
else:
# The application is not frozen
# Change this bit to match where you store your data files:
datadir = os.path.dirname(__file__)
return os.path.join(datadir, filename)
另一種方法是在代碼中嵌入數據,例如使用 Qt 的資源系統。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.