Python json.load() 在 PHP exec() 中不起作用

Python json.load() doesn't work in PHP exec()


我有一个 python 脚本,我希望使用 exec() 函数从 PHP 运行。 Python 脚本的作用是从网络 API 获取一些数据,将数据存储在临时文件中,然后读取文件并将一些数据放入 csv 文件中。脚本运行单独测试没问题。现在,我想通过 exec() 运行 它。当我第一次尝试时,我认为脚本根本不是 运行ning,但后来我进一步查看并意识到脚本实际上是 运行ning,但在执行过程中停在了某个地方.

然后我尝试使用 > output.txt 将输出重定向到一个 txt 文件,以查看哪里出错了。当我签入文件并稍作调试时,我意识到问题出在我的 Python 脚本中的函数 json.load() 上。奇怪的是,在output.txt文件中,并没有显示错误信息。

这是 output.txt 文件的样子。

这里是包含 json.load().

的 python 函数
def get_json_files_data(path, min = 1):

    json_files = find_files(path, "json", min)
    json_data = dict()

    print("===========================================")
    print("= Converting JSON data into Python object =")
    print("===========================================")

    for file in json_files:
        base = os.path.basename(file) # name with extension (ex. 'file.json')
        id = os.path.splitext(base)[0] # name without extension (ex. 'file') in this case, the names are the trip ids
        opened_file = open(file)
        print(10)
        json_data[id] = json.load(opened_file)  # get the json data as a python dict
        print(11)
    return json_data

我也尝试将 json 文件的权限更改为 777,但这并没有解决问题。

有人知道吗?让我知道是否需要更多代码。

非常感谢

我终于成功了。如果有人想知道,这里是解决方案。

问题出在编码上。根据我运行脚本的方式,它在某种程度上有所不同。我所做的只是用 encoding='utf-8' 指定编码。这是我的代码现在的样子。

def get_json_files_data(path, min = 1):

    json_files = find_files(path, "json", min)
    json_data = dict()

    print("===========================================")
    print("= Converting JSON data into Python object =")
    print("===========================================")
    for file in json_files:
        base = os.path.basename(file) # name with extension (ex. 'file.json')
        id = os.path.splitext(base)[0] # name without extension (ex. 'file') in this case, the names are the trip ids
        with open(file, 'r', encoding='utf-8') as opened_file:
            json_data[id] = json.load(opened_file)  # get the json data as a python dict

    return json_data