gpt4 book ai didi

python - 如何保存使用子进程循环 python 脚本的脚本的输出?

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

如何保存循环Python脚本的Python脚本的输出

from datetime import datetime
import faker
import json
from faker import Faker
import random
from random import randint
import subprocess
import json
import os
from pprint import pprint
import subprocess
import sys


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

此代码循环生成随机 json 文件的 python 脚本。每次循环时我都需要保存输出..

curl.py 代码,生成随机 json 并将输出保存到 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','7f36')

fake = Faker('en_US')

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
#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))


最佳答案

您可以添加一个运行 20 次的整体 for 循环,收集列表中的所有字典,然后将该列表保存为单个文件中的字典

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 _ 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)


#Saving overall data to a single dictionary and to a file
data = {"data":msg_list}

f_name = 'data.json'
with open(f_name, 'w') as fp:
#Save the dictionary
json.dump(data, fp, indent=4)
print('saved {}'.format(f_name))

data.json 看起来像

{
"data": [
{
"messages": [
{
"id": "AB-Iasd",
"body": "Up west accept third success bad.",
"reae": "0181541986524",
"ashe": "1490107025812",
"id2": "4087146706078",
"user_id": "5cda",
"pid": "Color wish method population affect."
},
{
"id": "AB-Iasd",
"body": "Human expect news son room recognize beautiful.",
"reae": "9417635708941",
"ashe": "0920108608482",
"id2": "8218562976929",
.....

关于python - 如何保存使用子进程循环 python 脚本的脚本的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56142106/

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