If you only need to support Linux and you just need to change the process name then you can simply write it to /proc/self/comm
.
Example:
import os
import subprocess
print(subprocess.run(['pidof', 'foo'], stdout=subprocess.PIPE,
universal_newlines=True))
print(subprocess.check_output(['ps', 'p', str(os.getpid()), '-o', 'pid,comm,cmd'],
universal_newlines=True))
with open(f'/proc/self/comm', 'w') as f:
f.write('foo')
print(subprocess.check_output(['pidof', 'foo'], universal_newlines=True))
print(subprocess.check_output(['ps', 'p', str(os.getpid()), '-o', 'pid,comm,cmd'],
universal_newlines=True))
Output:
$ python3 test.py argone argtwo
CompletedProcess(args=['pidof', 'foo'], returncode=1, stdout='')
PID COMMAND CMD
2881003 python3 test.py python3 test.py argone argtwo
2881003
PID COMMAND CMD
2881003 foo python3 test.py argone argtwo
NB: On Linux, in a C program, writing to argv[0]
just changes the argument in /proc/self/cmdline
and not in /proc/self/comm
. Thus, it doesn't affect pidof
, the top
COMMAND column, the ps
COMMAND column, plain pgrep
etc.
The setproctitle package supports multiple platforms and - on Linux - changes both the command and the argument vector. However, it's a C extension.