找不到pyinstaller附加数据文件

时间:2019-08-13 15:26:40

标签: python pyinstaller

我正在尝试从一个非常简单的读取json文件的python文件制作可执行文件。

在我的文件夹中只有这两个文件:

$wc_query_params = array(
     'post_type' => 'product_variation',
     'posts_per_page' => -1,
     'numberposts'   => -1,
     'post_status'   => 'publish',
     'meta_query'     => array(array(
         //filter variations on attribute name
         'key'  => 'attribute_pa_color',
         'value'     => 'blue', 
     )),
     'order'         => 'ASC',
     'orderby'       => 'menu_order',
 );
 $wc_query = new WP_Query($wc_query_params);

 if ($wc_query->have_posts()) :
     while ($wc_query->have_posts()) :
         $wc_query->the_post();

     //results

     endwhile;
     wp_reset_postdata();
 endif;

所以我跑:

test.py
data.json

这将创建一个dist文件夹,我可以在其中找到我的pyinstaller -F --add-data "data.json;data.json" test.py 。但是,当我运行exe文件时,找不到data.json

test.exe

我的文件非常简单:

FileNotFoundError: [Errno 2] No such file or directory: 'data.json'
[18556] Failed to execute script test

编辑:

好吧,看起来当我编译exe时,我必须从编译它的同一文件夹中执行它,所以我必须这样做:

import json

# data.json is in the same folder as test.py, so no path is provided
with open("data.json") as f:
    data = json.load(f)
    print(data)

如果我将文件夹更改为dist,然后从那里执行文件,则无法正常工作

./dist/test.exe

这显然不是我想要的。我应该能够从我想要的任何文件夹中调用exe。 data.json是包含在test.py所在的文件夹中的,因此在exe文件中,它们也应该位于同一“文件夹”中

1 个答案:

答案 0 :(得分:0)

将其添加到运行脚本的顶部。

import sys, os

os.chdir(sys._MEIPASS)

这应该可以解决问题。之所以起作用,是因为使用一种文件模式时;每次运行该应用程序时,都会在您的计算机temp文件夹中创建一个新目录。然后将所有依赖项解压缩到此文件夹中。 Pyinstaller将此目录存储在sys._MEIPASS中。因此,如果要使用相对路径,则需要更改cwd以访问文件。

相关问题