You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python读取JSON触发JSONDecodeError报错求助

解决JSON文件为空的问题

以下是针对你的问题的具体排查和解决步骤:

  • 确保subprocess等待PowerShell脚本执行完成
    Python如果在PowerShell脚本还没写完文件就尝试读取,会得到空内容。必须等待子进程执行完毕再处理文件:

    # 推荐用subprocess.run,默认等待进程结束,check=True会捕获脚本执行错误
    subprocess.run(["powershell.exe", ".\\your_script.ps1"], check=True)
    
    # 如果用Popen,必须显式等待
    proc = subprocess.Popen(["powershell.exe", ".\\your_script.ps1"])
    return_code = proc.wait() # 等待脚本执行完成,返回退出码
    if return_code != 0:
        raise Exception("PowerShell脚本执行失败")
    
  • 统一工作目录,避免路径歧义
    即使Python切换了目录,PowerShell的工作目录可能和Python当前目录不一致。调用subprocess时指定cwd参数,强制PowerShell在目标目录下执行:

    import os
    timestamp_dir = "20240520_1430" # 你的时间戳目录
    os.makedirs(timestamp_dir, exist_ok=True)
    # 调用脚本时指定工作目录为新创建的目录
    subprocess.run(["powershell.exe", ".\\your_script.ps1"], cwd=timestamp_dir, check=True)
    

    同时,PowerShell脚本里的输出路径尽量用相对路径,或者基于当前工作目录生成绝对路径:

    $outputFile = Join-Path $PWD.Path "result.json"
    # 生成JSON内容并写入
    $yourData | ConvertTo-Json | Out-File -Path $outputFile -Encoding UTF8
    
  • 检查PowerShell脚本的写入逻辑
    确认脚本里的写入操作是同步完成的:

    • 避免使用异步写入的方式,比如后台线程写入
    • 如果用Out-File,确保没有遗漏参数导致写入失败,比如指定正确的编码(UTF8)
    • 若使用文件流操作,必须显式关闭流:
      $stream = [System.IO.File]::CreateText("result.json")
      try {
          $stream.Write($jsonContent)
          $stream.Flush()
      } finally {
          $stream.Close()
      }
      
  • 提前验证文件状态
    在读取JSON前,先检查文件大小,确认内容已写入:

    json_file_path = "result.json"
    if os.path.getsize(json_file_path) == 0:
        raise Exception("JSON文件为空,PowerShell脚本未写入内容")
    # 再读取文件
    with open(json_file_path, "r", encoding="utf8") as f:
        content = f.read()
        print(content)
        data = json.loads(content)
    

内容的提问来源于stack exchange,提问作者Tarun Gupta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 05:35:20