Skip to content Skip to sidebar Skip to footer

How To Save The Output (json File)of A Subprocess That Is In A Loop

this code send generates a random json file of user ids provided and btw range is also given.. so this code outputs 50 jsons for each user. import faker import json from faker i

Solution 1:

You would want to bring the file saving logic inside the for ind in ids: loops, and use the index in the overall loop to save the file with different names.

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 timesfor i inrange(20):
    #Loop to generate messagesfor ind in ids:
        cont = []
        #Overall dictionary with first and user_ids
        dct = {}
        for idx inrange(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)
        withopen(f_name, 'w') as fp:
            # Save the dictionary
            json.dump(dct, fp, indent=4)
            print('saved {}'.format(f_name))

You will get 40 files as per your requirements, with unique content in all files.

Solution 2:

You can save the output of called python file to a file if you write the J-son into STDOUT and in loop.py redirect the STDOUT to a file. In you "generator" file: (Of course, you should remove other prints if you don't want to get invalid J-son file.)

...
dct['messages'] = cont
dct['user_id'] = ind
print(dct)
...

I your loop.py file:

subprocess.call(["ardbuf", "-oL", "python","grploop1.py", ">", test_folder/tmp_file.json])

Post a Comment for "How To Save The Output (json File)of A Subprocess That Is In A Loop"