当我双击可执行 Python 脚本(该脚本在 Linux 上使用 Pandas 读取 txt 文件)时,控制台立即打开并关闭

问题描述 投票:0回答:1

我使用

pyinstaller
创建了一个可执行的 Python 脚本,它可以使用 Pandas 读取
txt
文件。

当我通过终端运行它时,它工作正常,但是当我双击它时,控制台出现,然后立即消失。我还通过定义

.spec
更改了
datas=["./f.txt"]
文件,
hiddenimports=['pandas','os','numpy']
Python 脚本和
f.txt
位于同一目录下。

以下是脚本:

#!/usr/bin/python2
import os.path
import pandas as pd
import numpy as np

myfile = os.path.join(os.path.dirname(__file__), './f.txt')

df = pd.read_csv(myfile,sep='\s+,|\t',skiprows=[0,1,2,3,4,5,6,7,8,9,10,11,12], engine='python')

print df
input("Hit enter to close.")
python pandas csv pyinstaller txt
1个回答
0
投票

使用 pyinstaller 时,它将从“INSTALLATION_DIR/_internal”文件夹运行,因此很可能找不到“f.txt”文件,您可以通过从终端运行它来验证它,并且应该找到类似以下内容:

Traceback (most recent call last):
  File "a.py", line 7, in <module>
  File "pandas/io/parsers/readers.py", line 1026, in read_csv
  File "pandas/io/parsers/readers.py", line 620, in _read
  File "pandas/io/parsers/readers.py", line 1620, in __init__
  File "pandas/io/parsers/readers.py", line 1880, in _make_engine
  File "pandas/io/common.py", line 873, in get_handle
FileNotFoundError: [Errno 2] No such file or directory: '/tmp/dist/a/_internal/./f.txt'
[38960] Failed to execute script 'a' due to unhandled exception!

如果您遇到这种情况,您有 2 种可能的解决方案:

  1. 手动添加到_internal文件夹
  2. ‘编译’时,将其添加为数据源:
pyinstaller --add-data f.txt:. script.py
© www.soinside.com 2019 - 2024. All rights reserved.