pythonpyngrok

How can I prevent my python program from loading when using pyngrok?


I have the following function in my script

import os, re

from pyngrok import ngrok

def server():
        os.system('kill -9 $(pgrep ngrok)')
        ngrok.connect(443, "tcp")
        while True:
                ngrok_tunnels = ngrok.get_tunnels()
                url = ngrok_tunnels[0].public_url
                if re.match("tcp://[0-9]*.tcp.ngrok.io:[0-9]*", url) is not None:
                        print "your url is : " + url
                        break

This is responsible for generating a ngrok tcp link and it works, but it gets stuck like in the image below.

enter image description here

How can I prevent it from being charged? And just print the link, they told me about the monitor_thread mode in False but I don't know how to configure it in my function, thank you very much in advance.


Solution

  • The reason the script is “stuck” is because pyngrok starts ngrok with a thread to monitor logs, and the Python process can’t exit until all threads have been dealt with. You can stop the monitor thread, as shown here in the documentation, or, if you have no use for it, you can prevent it from starting in the first place:

    
    import os, re
    
    from pyngrok import ngrok
    from pyngrok.conf import PyngrokConfig
    
    def server():
        os.system('kill -9 $(pgrep ngrok)')
        ngrok_tunnel = ngrok.connect(443, "tcp", pyngrok_config=PyngrokConfig(monitor_thread=False))
        print("your url is : " + ngrok_tunnel.public_url)
    

    However, this still won’t do what you want. If you do this, yes, you will be returned back to the console, but with that the ngrok process will also be stopped, as it is a subprocess of Python at this point. To leave the tunnels open, you need to leave the process running.