Program Tip

Python에서 효과적인 프로세스 이름을 변경하는 방법이 있습니까?

programtip 2020. 10. 26. 08:28
반응형

Python에서 효과적인 프로세스 이름을 변경하는 방법이 있습니까?


Python 스크립트의 유효 프로세스 이름을 변경할 수 있습니까? 시스템 프로세스 목록을 가져올 때 프로세스의 실제 이름 대신 다른 이름을 표시하고 싶습니다. CI에서 설정할 수 있습니다.

strcpy(argv[0],"othername");

하지만 파이썬에서는

argv[0] = "othername"

작동하지 않는 것 같습니다. 프로세스 목록 ( ps ax내 Linux 상자에 있음)을받을 때 실제 이름이 변경되지 않습니다. 휴대용 솔루션 (또는 posix 용 솔루션과 Windows 환경 용 솔루션)이 있다면 선호합니다.

미리 감사드립니다


간단히 말해, 휴대용 방법이 없습니다. 시스템을 테스트하고 해당 시스템에 대해 선호하는 방법을 사용해야합니다.

또한 Windows에서 프로세스 이름이 의미하는 바에 대해 혼란 스럽습니다.

서비스 이름을 의미합니까? 나는 그렇게 생각한다. 왜냐하면 다른 것은 정말로 의미가 없기 때문이다 (적어도 두뇌를 사용하는 나의 비 Windows에게는).

그렇다면 Tim Golden의 WMI 인터페이스 를 사용 하고 적어도 그의 자습서 에 따라 서비스에서 .Change 메서드를 호출해야합니다 .

Linux의 경우 argv [0]을 설정하는 잘못 패키지 된 모듈제외하고는 내가 찾은 방법 중 어느 것도 작동 하지 않았습니다 .

나는 이것이 BSD 변형 (setproctitle 시스템 호출이 있음)에서 작동하는지조차 알지 못합니다. 저는 argv [0]이 Solaris에서 작동하지 않을 것이라고 확신합니다.


최근에 이식 가능한 방식으로 프로세스 제목을 변경하는 Python 모듈을 작성했습니다. https://github.com/dvarrazzo/py-setproctitle 확인

제목 변경을 수행하기 위해 PostgreSQL에서 사용하는 코드를 감싸는 래퍼입니다. 현재 Linux 및 Mac OS X에 대해 테스트되었습니다. Windows (제한된 기능 포함) 및 BSD 포팅이 진행 중입니다.

편집 : 2010 년 7 월 현재이 모듈은 BSD와 Windows에서 제한된 기능으로 작동하며 Python 3.x로 포팅되었습니다.


실제로 리눅스에서는 두 가지가 필요합니다 : (for 및 friends) argv[0]에서 수정 하고 플래그로 호출하십시오 .Cps auxfprctlPR_SET_NAME

파이썬 자체에서 첫 번째 조각을 할 수있는 방법은 전혀 없습니다. 그러나 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.value

import sys
# sys.argv[0] == 'python'

# outputs 'python'
get_proc_name()

set_proc_name('testing yeah')

# outputs 'testing yeah'
get_proc_name()

ps auxf그 :( 후 바로 '파이썬'을 보여줄 것이다. 그러나 topps -A프로세스 이름을 : '그래 테스트'새로운 표시됩니다. 또한 killallpkill새 이름으로 작동합니다.

btw, googlecode의 procname도 변경 argv[0]되므로 ps auxf출력 도 변경 됩니다.

업데이트 :이 답변에 게시 된 솔루션은 때때로 FreeBSD에서 잘 작동하지 않습니다. 나는 이제이 답변명시된 py-setproctitle 을 다양한 Linux 및 freebsd 상자에서 1 년 정도 사용하고 있습니다. 지금까지 실패하지 않았습니다! 모두가해야합니다! :). PostgreSQL 이 기본 데이터베이스 및 하위 프로세스에서 사용 하는 것과 거의 동일한 코드를 사용 합니다.


setproctitle 패키지 살펴보기

이것은 꽤 이식 가능한 버전이며 많은 플랫폼에서 작동합니다.


첫째, argv[0]C 프로그램의 설정이 에 표시된 이름을 이식 가능하게 변경 하는지 잘 모르겠습니다 ps. 아마도 일부 유닉스에서 할 수 있지만 내 이해는 그것이 예상되지 않는다는 것입니다.

Second, since Windows is specifically non-POSIX compliant, only a few things are "portable" between POSIX and non-POSIX. Since you specifically say 'ps', I'll assume that POSIX is your priority and Windows may not work.

More importantly, my understanding of changing argv[0] is that it requires a call to exec to make these changes. Specifically, the exec call has both a path to an executable and a separate argv list. Making your own call allows you to break the shell convention of putting the executable name in argv[0].

You have OS library process management which gives you direct access to the OS library for doing this. You should consider breaking your script into two parts -- a starter and the "real work". The starter establishes the run-time environment and exec's the real work with the desired parameters.

In C, you're replacing your own process with another. In Python, you're replacing the old Python interpreter with a new one that has a different argv[0]. Hopefully, it won't balk at this. Some programs check argv[0] to decide what they're doing.

You also have subprocess.popen that you can use to set your desired args and executable. In this case, however, the parent process should lingers around to collect the child when the child finishes. The parent may not be doing anything more than a Popen.wait


My answer to similar question marked as duplicate:

There is simplier (you don't need import any libs) but maybe not so elegant way. You have to do not use "env" inside the shebang line.

In other words, this will be named as "python" in process list:

#!/usr/bin/env python

But this will be named with your scriptname:

#!/usr/bin/python

So you'll be able to find it with something like pidof -x scriptname or ps -C scriptname


I have found python-prctl to work very well under Linux. You will have to find something else for Windows.


In [1]: import sys

In [2]: print sys.argv[0]
C:\Python25\scripts\ipython.py

In [3]: sys.argv[0] = 'foo'

In [4]: print sys.argv[0]
foo

Note the single '=' sign

참고URL : https://stackoverflow.com/questions/564695/is-there-a-way-to-change-effective-process-name-in-python

반응형