【问题标题】:how to load json file output(subprocess) into a variable in python?如何将json文件输出(子进程)加载到python中的变量中?
【发布时间】:2019-06-19 18:06:08
【问题描述】:

有一个每次生成随机数据的 python 代码。我使用子进程运行它。

first.py

代码:

for _ in range(50):
sms =  {

    "name": fake.name(),
    "email": fake.email() 
      }


with open('sfirst.json', 'w') as outfile:
    json.dump(sms, outfile)

子进程:

  subprocess.call(["python","first.py")

输出:

    {

    "name": "elmaro",
    "email": "elmaro@gmail.com" 
      }

如何将值生成的每个输出存储在字典或 1,2,3,4,...50 中的任何其他有用格式中。以便我以后可以使用它们。

示例:

 here we are looping 50 times so 
 {
 "name1": elmaro,
  "email1": elamro@gmail.com,
 "name2": spetus,
  "email2": spetus@gmail.com
    ........
  ........
   }
  upto 50 times should be stored and when i call 

  data[email45] it should return the value stored

【问题讨论】:

  • 我建议将first.py 重写为包含您可以调用的函数的模块,该函数返回字典而不是将 JSON 编码的对象写入文件。
  • 你能详细说明一下吗?我是新人
  • 如果您可以直接使用第一个程序中的代码,请不要使用subprocess 运行另一个 Python 程序。
  • 我必须使用子进程,如果我们运行一次,first.py 将生成一个随机数据。如果我将子进程循环 50 次,它只存储最后更新的输出。我需要将这里的所有输出数据 50 个随机数据附加到 dict 中,以便我可以进一步使用它们

标签: python pandas loops subprocess


【解决方案1】:
from subprocess import check_output
out = check_output(["python","first.py"])

out 将包含命令生成的输出

output_dict = dict()
output_dict['you need code to compute this'] = out['name']
output_dict['you need code to compute this as well'] = out['email']

如果你不明白,请告诉我

output_dict = dict()

for loop in range(50):
    out = check_output(["python","first.py"])
    emailKey = str(loop) + 'email'
    nameKey = str(loop) + 'name'
    output_dict[nameKey] = out['name']
    output_dict[emailKey] = out['email']

【讨论】:

  • out will contain the output generated by the command。如果我们循环运行它会追加??
  • 所以你更新循环中的字典并在循环外声明它,这样它就不会被重新初始化
  • first.py 如果我们运行一次,将生成一个随机数据。如果我将子进程循环 50 次,它只存储最后更新的输出。我需要将这里的所有输出数据 50 个随机数据附加到 dict 中,以便我可以进一步使用它们
  • 更新了响应,我希望伪代码现在有意义
  • 肯定会检查并告诉你
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-04-22
  • 1970-01-01
  • 2017-12-21
  • 2013-01-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多