setting program name, like $0= in perl?

Nick Craig-Wood nick at craig-wood.com
Wed Jun 10 10:29:37 CEST 2009


mh at pixar.com <mh at pixar.com> wrote:
>  I'm sure this is a FAQ, but I certainly haven't been able
>  to find an answer.
> 
>  Is it possible to set the program name as seen by the
>  operating system or lower-level libraries?
> 
>  I'm connecting to a database, and the runtime helpfully
>  sends some information to the server, such as username,
>  pid, and program name.
> 
>  Unfortunately, all my python programs get the name
>  '/usr/bin/python', and I would like to force that to
>  be the names of the individual scripts.

You can use this module

  http://code.google.com/p/procname/

Just for fun I made a pure python version using ctypes

------------------------------------------------------------
#!/usr/bin/python
"""
Attempt to set the process name with ctypes
"""

import os
from subprocess import Popen, PIPE
from ctypes import pythonapi, c_int, c_char_p, POINTER, addressof, pointer, CDLL, memmove, memset
from ctypes.util import find_library

Py_GetArgcArgv = pythonapi.Py_GetArgcArgv

c_lib = CDLL(find_library("c"))
PR_SET_NAME = 15                        # linux specific

argc_t = POINTER(c_char_p)
Py_GetArgcArgv.restype = None
Py_GetArgcArgv.argtypes = [POINTER(c_int), POINTER(argc_t)]

def set_name(name):
    argv = c_int(0)
    argc = argc_t()
    Py_GetArgcArgv(argv, pointer(argc))
    name0 = name+"\0"
    memset(argc.contents, 0, 256)       # could do this better!
    memmove(argc.contents, name0, len(name0))
    # prctl doesn't seem to be needed on linux?
    c_lib.prctl(PR_SET_NAME, name+"\0", 0, 0, 0)

def ps():
    print Popen(["ps", "v", str(os.getpid())], stdout=PIPE).communicate()[0]
    
def main():
    print "Before"
    ps()
    set_name("sausage")
    print "After"
    ps()
    
if __name__ == "__main__":
    main()
------------------------------------------------------------
    
This prints

$ ./procname.py
Before
  PID TTY      STAT   TIME  MAJFL   TRS   DRS   RSS %MEM COMMAND
 9159 pts/7    S+     0:00      0  1000  5551  3404  0.1 /usr/bin/python ./procname.py

After
  PID TTY      STAT   TIME  MAJFL   TRS   DRS   RSS %MEM COMMAND
 9159 pts/7    S+     0:00      0  1000  5551  3420  0.1 sausage                


-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list