iOS debug log capture

I am using python to write appium automation scripts to test my app. How can I set up my script to capture ios logs and save them to a txt file. I have found that ‘idevicesys log > logfile.txt’ will do what I need, but I need to be able to call this within my script and stop the logcat at a specific point. How would I go about automating the start and stop of the log capture?

thank you!


    cmd = ['xcrun', 'simctl', 'spawn', 'booted', 'log', 'stream', '--level', 'debug', '--style', 'syslog']
    with open(filepath, 'w') as f:
        pid = subprocess.Popen(cmd, stdout=f)
    self.log_capture_pid = pid


    if self.log_capture_pid: