Start and stop mitmproxy from Python script

Hi all!
I wonder how to start and stop MITMProxy from a Python3 program. I need to programmatically start MITMProxy and exit it in a clean way in order to be sure that the output file is correctly flushed on disk.

Do you have any recommendations, hints, snippets, whatever about that?

Cheers!!

What exactly are you trying to accomplish? You can either run mitmdump as a regular process and send it a Ctrl+C when you are finished (importing mitmdump from mitmproxy.tools.main would work as well), or you instantiate your own DumpMaster and thenn call master.shutdown() when you are finished.

I solved this problem in my own script calling

from mitmproxy import ctx
ctx.master.shutdown()

mitmproxy v4.0.1

@Gigiarum and @mhils:
Can you please elaborate how to start and stop mitm programatically?

I create a system service that call my script launching mitmdump.