在 QProcess(Pyside6) 运行的脚本内打开网络内的文件

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

Python 脚本由 QProcess 执行。在此脚本中,应打开并写入特定文件。文件路径应始终为

\\127.0.0.1\folder\myfile.json

def write_to_json(IP, slice_id, json_lines):
    #IP = "127.0.0.1" (or any other network id as str)
    #slice_id = 1
    #json_lines: string

    output_file = r"\\{}\hatches\slice{}.json".format(IP, slice_id)

    subprocess.run(f"echo. >> {output_file}", shell=True)

    with open(output_file, "a") as f:    #also tried w
            for line in json_lines:
                f.write(line + '\n')  

当这段代码被IDE执行时,它工作正常并且可以找到Path。当使用 QProcess 运行时,文件系统似乎添加了随机反斜杠,因此无法找到路径:

[Errno 2] No such file or directory: '\\\\127.0.0.1\\hatches\\slice1.json'

还尝试了其他方法(除了使用 subprocess 解析到文件之外,因为每行的长度可能大于 48k 个元素,这超出了 Windows 中启用的路径长度的最大长度。否则使用解析文件的输入子流程会起作用):

  1. 将路径传递为

     output_file = r"{}\hatches\slice{}.json".format(IP, slice_id)
    

输出:

[Errno 2] No such file or directory: '127.0.0.1\\hatches\\slice1.json'
  1. 删除反斜杠会导致:

     output_file.remove(r"\\","")
    

输出: [Errno 2] 无法连接到网络“127.0.0.1hatchesslice1.json”

有人知道如何解决这个反斜杠问题吗? (synax不能更改,否则无法连接)。

python pyside6 qt6 qprocess
1个回答
0
投票

解决方案是为网络路径(例如 .0.0.1 旧版)提供一个驱动器名称,例如“M:/”,因此任何斜杠都可以用于访问它。

© www.soinside.com 2019 - 2024. All rights reserved.