0

Disclaimer, I am new to python.

I wanted to test Threads and especially daemons in Python, I wrote a simple application which calls an endpoint in a daemon every x - seconds. However when I pass a String to the target function, the value is empty:

Creation of the daemon:

daemon = threading.Thread(target=thread_function, args=(url,), daemon=True)
daemon.start()

Target function:

def thread_function(url):
    print("Thread operates with url: ", url)
    while True:
        data = call_endpoint(url)
        followers = parser(data)
        print("The selected account has {} followers!".format(followers))
        time.sleep(5)

Expected result:

Thread operates with url: https://www.instagram.com/username/?__a=1

Actual result:

Thread operates with url:

This is weird, because when I pass the int value 1 to the target function output is:

Thread operates with url: 1

Note the string url is not empty, I even tried:

daemon = threading.Thread(target=thread_function, args=("Hello",), daemon=True)

Output:

Thread operates with url:

Alan
  • 589
  • 5
  • 29
  • what python version are you using? I tried your code (the thread_function with just the print) and it works as expected – Yohanna Lisnichuk Jan 03 '20 at 15:04
  • Your main-thread is probably exiting right after starting the thread because there's not left anything to do and it won't wait for the daemon-thread to finish. Python's "daemon" for threads is not a Unix-daemon, it's just a thread which doesn't get joined when the main-thread shuts down. – Darkonaut Jan 03 '20 at 15:09
  • @YohannaLisnichuk You probably tested with IPython where the main-thread is kept alive anyway. – Darkonaut Jan 03 '20 at 15:12
  • I am using python 3, after i start the daemon there is no execution after it, the program is finished. I thought daemons still run in the background, also after the program is finished – Alan Jan 03 '20 at 15:22
  • @Darkonaut that was exactly the problem. Isn't there a workaround where the daemon keeps staying alive? – Alan Jan 03 '20 at 15:24
  • The main-thread is always the last thread which dies in a process, so it's not possible to keep other threads in the same process alive without the main-thread. A Unix-daemon is a "process". Python doesn't have an API for creating Unix-daemons as you intend. The known workaround for creating a Unix-daemon would be the double-fork strategy, but that's a complex topic, [see](https://stackoverflow.com/q/473620/9059420). Check out the [python-daemon](https://pypi.org/project/python-daemon/) module for an implementation. – Darkonaut Jan 03 '20 at 16:09
  • Thank you, so in my example an easy solution would just be a infinity loop? Quick and dirty? – Alan Jan 03 '20 at 16:19
  • 1
    You mean without another thread? Sure, not dirty at all. – Darkonaut Jan 03 '20 at 16:29

0 Answers0