在QProcess(Pyside6)运行的脚本中打开网络内的文件
一个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(集成开发环境)中执行时,一切正常,路径可以找到。但是当通过QProcess运行时,文件系统似乎会添加一些随机的反斜杠,导致路径无法找到:
[Errno 2] No such file or directory: '\\\\127.0.0.1\\hatches\\slice1.json'
还尝试了其他方法(除了使用subprocess来解析文件,因为每行的长度可能超过48k个元素,这超过了Windows中启用的最大路径长度。如果不是这样,使用subprocess解析输入文件是可行的):
将路径作为
output_file = r"{}\hatches\slice{}.json".format(IP, slice_id)
输出:
[Errno 2] No such file or directory: '127.0.0.1\\hatches\\slice1.json'
去掉反斜杠会导致:
output_file.remove(r"\\","")
输出: [Errno 2] 无法连接到网络 '127.0.0.1hatchesslice1.json'
有没有人知道怎么解决这个反斜杠的问题?(语法不能改变,否则就无法建立连接)。
1 个回答
暂无回答