Pit when pyinstaller packages python (py) scripts as exe files (os and sys)

Today, I wrote a simple batch script. In order to be used by colleagues who do not have an environment, it is packaged into an executable single exe file through pyinstaller -F xxx.py

When the py file was debugged, everything was normal, but after it was packaged into an exe file, the operation appeared to be a flashback. Finally, through the method of cmd command .\xxx.exe, it was found that WinError 123 error occurred. Through the investigation, it was found that after pyinstaller was packaged, os.path and sys.path were empty or some unexpected values. There must be a principle. But there is no further investigation here.

You can package and test the following code yourself:

import sys
import os
print(sys.path[0])
print(sys.argv[0])
print(os.path.dirname(os.path.realpath(sys.executable)))
print(os.path.dirname(os.path.realpath(sys.argv[0])))
————————————————
版权声明:本文为CSDN博主「买菇凉的小火披」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_31801903/article/details/81666124

Exception after running exe

Put the problem code below.

import os
import sys
import shutil
import time

#%%
#获取当前路径下所有文件夹
#os.path.abspath(__file__)

#1.获取当前文件所在路径
now_path = os.path.abspath(__file__)

print(now_path)
#切换工作路径到当前的空间
os.chdir(now_path)

#显示文件夹名
folders_path = os.listdir()
#判断文件数量,筛选获取只有1个文件的文件路径
#folder_name_noly_one = []
#%%
for i in folders_path:
    path = now_path + '\\' + i
    if os.path.isdir(i) and len(os.listdir(i)) == 1:
        file_path = path + '\\' + os.listdir(i)[0]
        #os.path.abspath(os.listdir(i))
        #i = os.path.abspath(os.listdir(i))
        #folder_name_noly_one.append(i)
        shutil.move(file_path,now_path)
        os.rmdir(path)
    else:
        continue

print('运行完成!')
time.sleep(5)
#将其内部文件剪切出来

The last modified code

#%%
import os
import sys
import shutil
import time
import tkinter as tk
from tkinter import filedialog
#%%
#获取当前路径下所有文件夹
#os.path.abspath(__file__)

#1.获取当前文件所在路径
now_path = filedialog.askdirectory()

print(now_path)
#切换工作路径到当前的空间
os.chdir(now_path)

#显示文件夹名
folders_path = os.listdir()
#判断文件数量,筛选获取只有1个文件的文件路径
#folder_name_noly_one = []
#%%
for i in folders_path:
    path = now_path + '\\' + i
    if os.path.isdir(i) and len(os.listdir(i)) == 1:
        file_path = path + '\\' + os.listdir(i)[0]
        #os.path.abspath(os.listdir(i))
        #i = os.path.abspath(os.listdir(i))
        #folder_name_noly_one.append(i)
        shutil.move(file_path,now_path)
        os.rmdir(path)
    else:
        continue

print('运行完成!')
time.sleep(5)
#将其内部文件剪切出来



#删除空文件夹

# %%

Guess you like

Origin blog.csdn.net/u010472858/article/details/105499736