此代码发送会生成一个随机的json文件,其中包含提供的用户ID和btw 范围也给定了。
因此此代码为每个用户输出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 < / p>
在这里,我们提供了两个用户ID ids= ('5cda','6cda')
,因此输出总共为40个json文件。
答案 0 :(得分:1)
您希望将文件保存逻辑带入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个文件,所有文件中的内容都是唯一的。
答案 1 :(得分:1)
如果将J子写入STDOUT并在loop.py中将STDOUT重定向到文件,则可以将调用的python文件的输出保存到文件中。 在您的“生成器”文件中:(当然,如果您不想获取无效的J子文件,则应该删除其他打印件。)
...
dct['messages'] = cont
dct['user_id'] = ind
print(dct)
...
我是您的loop.py文件:
subprocess.call(["ardbuf", "-oL", "python","grploop1.py", ">", test_folder/tmp_file.json])