Set process name in python

How to set process name from inside it? I know that nmap can fake name, but the question is how to do this from python.
The code that is doing this magic in nmap:

# from nmap.cc
if (quashargv) {
size_t fakeargvlen = strlen(FAKE_ARGV), argvlen = strlen(argv[0]);
if (argvlen < fakeargvlen)
fatal("If you want me to fake your argv, you need to call the program with a longer name. Try the full pathname, or rename it fyodorssuperdedouperportscanner");
strncpy(argv[0], FAKE_ARGV, fakeargvlen);
memset(&argv[0][fakeargvlen], '\0', strlen(&argv[0][fakeargvlen]));
for(i=1; i < argc; i++)
memset(argv[i], '\0', strlen(argv[i]));
There are some possible ways of doing this from python. Some guys suggest using prctl ioctl. But it didn't worked for me. Also the module proctitle haven't done what I expected.
From time I found rtgraph3d project, I'm a fan of PyInline module. Here's my python code that's working (for me):
import PyInline, time

m = PyInline.build(code=r"""
#include <Python.h>
#include <stdio.h>
#include <string.h>

void set_argv(char *str){
int argc;
char **argv;
Py_GetArgcArgv(&argc, &argv);
strncpy(argv[0], str , strlen(str));
memset(&argv[0][strlen(str)], '\0', strlen(&argv[0][strlen(str)]));
""", language="C")

m.set_argv('very custom python process name')
It looks funny from ps:
majek@tigger:~$ ps aux|grep very
majek 11688 2.6 0.4 7192 4360 pts/21 S+ 00:20 0:00 very custom python process name


Anonymous said...

Thank you for the recipe. Unfortunately to me PyInline crashed my program often. :( I don't know why - I have a big import list and it's not obvious to find which module caused crash.

I've written small python module procname for getting/setting process name.

Usage is extremally simple:
>>> import procname
>>> procname.getprocname()
>>> procname.setprocname('Bla-bla-bla')

This library affects both top and ps output.

It could be get here: http://code.google.com/p/procname/
Source code is less than 1KB!

Thanks for feedback!
Yours, Eugene

himdel said...

Um, the easy way is
sys.argv[0] = 'whatever'