This question already has an answer here:

I have a Python service in systemd. I'd like to have it use the Python syslog module for logging if it's running in systemd vs. otherwise. Is there a reliable way to determine if I'm running in systemd or is there a better way of going about it?

marked as duplicate by Jeff Schaller, jasonwryan, don_crissti, mdpc, Gilles Apr 5 '16 at 23:56

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • why not have your python program have a flag like --syslog, then pass that flag with the systemd service? – user530873 Apr 5 '16 at 21:31
  • I can do that. I was just wondering if there's still a way to determine whether I'm in SystemD. – Naftuli Kay Apr 5 '16 at 21:35
  • ps -q 1 -o comm=... – jasonwryan Apr 5 '16 at 21:43

systemd will always have a PID of 1, so you can check if the parent PID is 1:

import psutil, os
if psutil.Process(os.getpid()).ppid() == 1:
    # We are using systemd

However, it's probally better to offer a command line flag --syslog and pass that with the systemd service, this way the user can select to use syslog even without the systemd service.

  • Won't init also be pid 1? – Jeff Schaller Apr 5 '16 at 21:46
  • @JeffSchaller hence the reason I recommend the command line flag – user530873 Apr 5 '16 at 21:47

Not the answer you're looking for? Browse other questions tagged or ask your own question.