Filename reading problem when converting to exe with cx_Freeze module

huangapple go评论125阅读模式
英文:

Filename reading problem when converting to exe with cx_Freeze module

问题

我在Python中创建了一个名为dork.py的文件,并在文件中写入了以下内容:

```python
import os,time
    
print(os.path.basename(__file__))
time.sleep(3)

结果在屏幕上打印出dork.py
在我为cx_Freeze创建的setup.py中,我写入了以下内容:

from cx_Freeze import setup, Executable
    
build_exe_options = {
    'packages': ['os','time'],
    'include_files':['/']
}
    
setup(
    name='YourAppName',
    version='1.0',
    description='Your App Description',
    options={'build_exe': build_exe_options},
    executables=[Executable('dork.py')]
)

当我运行exe文件时,我希望它打印出dork.exe,但它显示dork.py。我尝试了使用pyinstaller,但pyinstaller报错了。

我该如何解决这个问题?

我期望它打印出dork.exe,但它显示dork.py。


<details>
<summary>英文:</summary>

I created a file called dork.py in Python and wrote the following inside the file:

import os,time

print(os.path.basename(file))
time.sleep(3)


as a result it prints dork.py on the screen
In the setup.py I created for cx_Freeze, I wrote the following:

from cx_Freeze import setup, Executable

build_exe_options = {
'packages': ['os','time'],
'include_files':['/']
}

setup(
name='YourAppName',
version='1.0',
description='Your App Description',
options={'build_exe': build_exe_options},
executables=[Executable('dork.py')]
)


When I run the exe file I want it to print dork.exe but it says dork.py. I tried this with pyinstaller and pyinstaller was giving an error

How can i solve this

I expected it to print dork.exe but it says dork.py

</details>


# 答案1
**得分**: 1

the `__file__` 在冻结后将指向原始的Python文件,这是cx_freeze或pyinstaller在冻结模块时如何"修补"这些变量的方式。

当应用程序被冻结时,使其返回`.exe` 的简单方法在[文档](https://cx-freeze.readthedocs.io/en/latest/faq.html#using-data-files)中有详细说明:

```python
import sys

if getattr(sys, "frozen", False):
    # 应用程序已被冻结
    script_path = sys.executable
else:
    # 应用程序未被冻结
    script_path = __file__

print(script_path)
英文:

the __file__ will point to the original python file after freezing, this is the way cx_freeze or pyinstaller "patches" these variables when it freezes the modules.

a simple way to make it return .exe when the app is frozen is outlined in the documentation

import sys

if getattr(sys, &quot;frozen&quot;, False):
    # The application is frozen
    script_path = sys.executable
else:
    # The application is not frozen
    script_path = __file__

print(script_path)

huangapple
  • 本文由 发表于 2023年2月16日 18:50:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/75471188.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定