【问题标题】:os.environ doesn't find actual file path after pyinstalleros.environ 在 pyinstaller 之后找不到实际的文件路径
【发布时间】:2021-10-18 08:59:55
【问题描述】:

我基本上需要访问filekey.key,它位于 python 文件和 pyinstalled 可执行文件的同一目录中。我知道我必须正确处理文件位置,以便检查 _MEIPASS2。但它不起作用。

我也在使用--onefile。代码更有说服力。

Python 文件

from cryptography.fernet import Fernet
import os
filename = 'filekey.key' 
if '_MEIPASS2' in os.environ:
    filename = os.path.join(os.environ['_MEIPASS2'], filename)

with open(filename, 'rb') as filekey:
    key = filekey.read()

我也尝试过使用批处理文件来启动它,但没有成功。

运行 .exe 时出错

Traceback (most recent call last):
  File "launch.py", line 7, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'filekey.key'

【问题讨论】:

  • 您是否尝试显式设置 cwd;例如os.path.join(os.getcwd(), filename)?
  • 我没有。这解决了问题!谢谢

标签: python python-3.x path pyinstaller python-cryptography


【解决方案1】:

我运行这段代码没有出错:

from cryptography.fernet import Fernet
import os

key = Fernet.generate_key()

filename = 'filekey.key' 

with open(filename, 'wb') as mykey:
    mykey.write(key)

    
if '_MEIPASS2' in os.environ:
    filename = os.path.join(os.environ['_MEIPASS2'], filename)
    
  
with open(filename, 'rb') as filekey:
    key = filekey.read()
    
print(key)

【讨论】:

  • 我也没有。如果我运行 .exe,我会收到错误消息。
  • @Madernfader,你在 os.environ 中有 '_MEIPASS2' 吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-05-09
  • 2012-03-24
  • 2022-11-17
  • 1970-01-01
  • 2019-02-28
  • 1970-01-01
  • 2014-01-24
相关资源
最近更新 更多