Is there a way to change effective process name in Python? Is there a way to change effective process name in Python? python python

Is there a way to change effective process name in Python?


I've recently written a Python module to change the process title in a portable way: check https://github.com/dvarrazzo/py-setproctitle

It is a wrapper around the code used by PostgreSQL to perform the title change. It is currently tested against Linux and Mac OS X: Windows (with limited functionality) and BSD portings are on the way.

Edit: as of July 2010, the module works with BSD and with limited functionality on Windows, and has been ported to Python 3.x.


actually you need 2 things on linux: modify argv[0] from C (for ps auxf and friends) and call prctl with PR_SET_NAME flag.

There is absolutely no way to do first piece from python itself. Although, you can just change process name by calling prctl.

def set_proc_name(newname):    from ctypes import cdll, byref, create_string_buffer    libc = cdll.LoadLibrary('libc.so.6')    buff = create_string_buffer(len(newname)+1)    buff.value = newname    libc.prctl(15, byref(buff), 0, 0, 0)def get_proc_name():    from ctypes import cdll, byref, create_string_buffer    libc = cdll.LoadLibrary('libc.so.6')    buff = create_string_buffer(128)    # 16 == PR_GET_NAME from <linux/prctl.h>    libc.prctl(16, byref(buff), 0, 0, 0)    return buff.valueimport sys# sys.argv[0] == 'python'# outputs 'python'get_proc_name()set_proc_name('testing yeah')# outputs 'testing yeah'get_proc_name()

ps auxf will show just 'python' after that :(. But top and ps -A will show new 'testing yeah' process name :). Also killall and pkill will work with new name.

btw, procname from googlecode also changes argv[0], thus, even, changes ps auxf output.

UPDATE: The solution posted in this answer does not play nice sometimes on FreeBSD. I'm now using py-setproctitle stated in this answer for a year or so on various linux and freebsd boxes. No fails so far! Everybody should too! :). It uses almost the same code as PostgreSQL uses in its main database and child processes.


Have a look on setproctitle package

This is quite a portable version and works on many platforms.

pip install setproctitle

 

import setproctitlesetproctitle.setproctitle('new proc title as seen in top')