gpt4 book ai didi

python - 如何保存循环中子进程的输出(json 文件)

转载 作者:太空宇宙 更新时间:2023-11-03 20:53:50 25 4
gpt4 key购买 nike

此代码发送生成一个随机 json 文件,其中包含提供的用户 ID 和顺便说一句 还给出了范围..

因此此代码为每个用户输出 50 个 json。

import faker
import json
from faker import Faker
import random
from random import randint
import subprocess
import json
import os
#subprocess.call([""])
from pprint import pprint

ids= ('5cda','6cda')

fake = Faker('en_US')

for ind in ids:
cont = []
#Overall dictionary with first and user_ids
dct = {}
for idx in range(50):

sms = {
"id":"AB-asfgw",
"body": fake.text(),
"mime": fake.ean(),
"hashed": fake.ean(),
"pid": fake.ean(),
"user_id": ind,
"text": fake.sentence()
}
cont.append(sms)

dct['messages'] = cont
dct['user_id'] = ind
#print(dct)
f_name = '{}.json'.format(ind)
with open(f_name, 'w') as fp:
#Save the dictionary
json.dump(dct, fp, indent=4)
print('saved {}'.format(f_name))

auth = "authorization: token 1324"
file = "5cda.json"
fd=open("5cda.json")
json_content = fd.read()
fd.close()


subprocess.run(["grpcurl", "-plaintext","-H", auth,"-d",json_content,"-format","json","100.20.20.1:5000","api.Service/Method"])


这个loop.py代码循环第一个代码20次

from datetime import datetime
import faker
import json
from faker import Faker
import random
from random import randint
import subprocess
import json
import os
#subprocess.call([""])
from pprint import pprint
import subprocess
import sys



for i in range(20):
subprocess.call(['python','grploop1.py'])

我需要保存每个循环的loop.py代码的输出。并存储该 json。示例:我们在loop.py中循环第一个代码20次,因此存储的输出应该像5cda1.json ........ 5cda20.json和6cda1.json ..... 6cda20.json

这里我们给出了两个用户 ID ids= ('5cda','6cda') 因此输出总共是 40 个 json 文件。

最佳答案

您可能希望将文件保存逻辑引入到 for ind in ids: 循环中,并在整个循环中使用索引以不同的名称保存文件。

import faker
import json
from faker import Faker
import random
from random import randint
import subprocess
import json
import os
#subprocess.call([""])
from pprint import pprint

ids= ('5cda','7f36')

fake = Faker('en_US')

msg_list = []

#Overall loop to run inner loop 20 times
for i in range(20):
#Loop to generate messages
for ind in ids:
cont = []
#Overall dictionary with first and user_ids
dct = {}
for idx in range(20):


sms = {
"id":"AB-Iasd",
"body": fake.sentence(),
"reae": fake.ean(),
"ashe": fake.ean(),
"id2": fake.ean(),
"user_id": ind,
"pid": fake.sentence()
}
cont.append(sms)
#Use a dictionary to save cont list to first key, and ind to user_ids key
dct['messages'] = cont
dct['user_id'] = ind
msg_list.append(dct)

#Append the index to the file here, and save the file
f_name = '{}{}.json'.format(ind,i+1)
with open(f_name, 'w') as fp:
# Save the dictionary
json.dump(dct, fp, indent=4)
print('saved {}'.format(f_name))

您将根据您的要求获得 40 个文件,所有文件中都有独特的内容。

关于python - 如何保存循环中子进程的输出(json 文件),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56144385/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com