Hướng dẫn python check process running - quá trình kiểm tra python đang chạy

Tôi đang cố gắng tạo ra một kịch bản Python mà sau này tôi sẽ chạy như một dịch vụ. Bây giờ tôi chỉ muốn chạy một phần cụ thể của mã khi iTunes đang chạy. Tôi hiểu từ một số nghiên cứu rằng bỏ phiếu toàn bộ danh sách lệnh và sau đó tìm kiếm ứng dụng cho danh sách đó là tốn kém.

Tôi phát hiện ra rằng các quy trình trên các hệ điều hành dựa trên UNIX tạo một tệp khóa để thông báo rằng chương trình hiện đang chạy, tại thời điểm đó chúng ta có thể sử dụng

# get info dict about all running processes
import subprocess
output = subprocess.check_output(('TASKLIST', '/FO', 'CSV')).decode()
# get rid of extra " and split into lines
output = output.replace('"', '').split('\r\n')
keys = output[0].split(',')
proc_list = [i.split(',') for i in output[1:] if i]
# make dict with proc names as keys and dicts with the extra nfo as values
proc_dict = dict((i[0], dict(zip(keys[1:], i[1:]))) for i in proc_list)
for name, values in sorted(proc_dict.items(), key=lambda x: x[0].lower()):
    print('%s: %s' % (name, values))
0 để kiểm tra xem tệp có tồn tại để xác định xem chương trình có chạy hay không.

Có một tệp khóa tương tự được tạo trên Windows không?

Nếu không phải là những cách khác nhau trong Python mà theo đó chúng ta có thể xác định xem một quá trình có đang chạy hay không?

Tôi đang sử dụng giao diện Python 2.7 và iTunes com.

Hướng dẫn python check process running - quá trình kiểm tra python đang chạy

Martineau

Huy hiệu vàng 116K2525 gold badges161 silver badges286 bronze badges

Hỏi ngày 16 tháng 10 năm 2011 lúc 20:33Oct 16, 2011 at 20:33

3

Bạn không thể dựa vào các tệp khóa trong Linux hoặc Windows. Tôi sẽ chỉ cắn viên đạn và lặp lại thông qua tất cả các chương trình đang chạy. Tôi thực sự không tin rằng nó sẽ "đắt tiền" như bạn nghĩ. PSUTIL là một cáp mô-đun Python đa nền tảng tuyệt vời để liệt kê tất cả các chương trình đang chạy trên một hệ thống.

import psutil    
"someProgram" in (p.name() for p in psutil.process_iter())

Hướng dẫn python check process running - quá trình kiểm tra python đang chạy

monk-time

1.88312 Huy hiệu bạc17 Huy hiệu đồng12 silver badges17 bronze badges

Đã trả lời ngày 17 tháng 10 năm 2011 lúc 1:54Oct 17, 2011 at 1:54

Hướng dẫn python check process running - quá trình kiểm tra python đang chạy

MarkmarkMark

105K18 Huy hiệu vàng167 Huy hiệu bạc228 Huy hiệu Đồng18 gold badges167 silver badges228 bronze badges

8

Mặc dù @zeller đã nói rằng đây là một ví dụ về cách sử dụng

# get info dict about all running processes
import subprocess
output = subprocess.check_output(('TASKLIST', '/FO', 'CSV')).decode()
# get rid of extra " and split into lines
output = output.replace('"', '').split('\r\n')
keys = output[0].split(',')
proc_list = [i.split(',') for i in output[1:] if i]
# make dict with proc names as keys and dicts with the extra nfo as values
proc_dict = dict((i[0], dict(zip(keys[1:], i[1:]))) for i in proc_list)
for name, values in sorted(proc_dict.items(), key=lambda x: x[0].lower()):
    print('%s: %s' % (name, values))
1. Vì tôi chỉ đang tìm kiếm các lựa chọn thay thế vani Python ...vanilla python alternatives...

import subprocess

def process_exists(process_name):
    call = 'TASKLIST', '/FI', 'imagename eq %s' % process_name
    # use buildin check_output right away
    output = subprocess.check_output(call).decode()
    # check in last line for process name
    last_line = output.strip().split('\r\n')[-1]
    # because Fail message could be translated
    return last_line.lower().startswith(process_name.lower())

Và bây giờ bạn có thể làm:

>>> process_exists('eclipse.exe')
True

>>> process_exists('AJKGVSJGSCSeclipse.exe')
False

Để tránh gọi đây nhiều lần và có cái nhìn tổng quan về tất cả các quy trình theo cách này bạn có thể làm điều gì đó như:

# get info dict about all running processes
import subprocess
output = subprocess.check_output(('TASKLIST', '/FO', 'CSV')).decode()
# get rid of extra " and split into lines
output = output.replace('"', '').split('\r\n')
keys = output[0].split(',')
proc_list = [i.split(',') for i in output[1:] if i]
# make dict with proc names as keys and dicts with the extra nfo as values
proc_dict = dict((i[0], dict(zip(keys[1:], i[1:]))) for i in proc_list)
for name, values in sorted(proc_dict.items(), key=lambda x: x[0].lower()):
    print('%s: %s' % (name, values))

Đã trả lời ngày 26 tháng 3 năm 2015 lúc 9:50Mar 26, 2015 at 9:50

Ewerybodyewerybodyewerybody

1.31313 Huy hiệu bạc28 Huy hiệu đồng13 silver badges28 bronze badges

6

# get info dict about all running processes
import subprocess
output = subprocess.check_output(('TASKLIST', '/FO', 'CSV')).decode()
# get rid of extra " and split into lines
output = output.replace('"', '').split('\r\n')
keys = output[0].split(',')
proc_list = [i.split(',') for i in output[1:] if i]
# make dict with proc names as keys and dicts with the extra nfo as values
proc_dict = dict((i[0], dict(zip(keys[1:], i[1:]))) for i in proc_list)
for name, values in sorted(proc_dict.items(), key=lambda x: x[0].lower()):
    print('%s: %s' % (name, values))
2 Trả về một tay cầm cửa sổ nếu bất kỳ cửa sổ nào có tên lớp đã cho. Nó tăng
# get info dict about all running processes
import subprocess
output = subprocess.check_output(('TASKLIST', '/FO', 'CSV')).decode()
# get rid of extra " and split into lines
output = output.replace('"', '').split('\r\n')
keys = output[0].split(',')
proc_list = [i.split(',') for i in output[1:] if i]
# make dict with proc names as keys and dicts with the extra nfo as values
proc_dict = dict((i[0], dict(zip(keys[1:], i[1:]))) for i in proc_list)
for name, values in sorted(proc_dict.items(), key=lambda x: x[0].lower()):
    print('%s: %s' % (name, values))
3 nếu không.

import win32ui

def WindowExists(classname):
    try:
        win32ui.FindWindow(classname, None)
    except win32ui.error:
        return False
    else:
        return True

if WindowExists("DropboxTrayIcon"):
    print "Dropbox is running, sir."
else:
    print "Dropbox is running..... not."

Tôi thấy rằng tên lớp cửa sổ cho biểu tượng khay Dropbox là DropboxTrayicon bằng cách sử dụng Spy Window Autohotkey.

Xem thêm

MSDN FindWindow

Đã trả lời ngày 20 tháng 8 năm 2012 lúc 16:17Aug 20, 2012 at 16:17

Jisang Yoojisang YooJisang Yoo

3.56019 huy hiệu bạc31 huy hiệu đồng19 silver badges31 bronze badges

2

Các tệp khóa thường không được sử dụng trên Windows (và hiếm khi trên Unix). Thông thường khi một chương trình Windows muốn xem liệu một phiên bản khác của chính nó đã chạy, nó sẽ gọi

# get info dict about all running processes
import subprocess
output = subprocess.check_output(('TASKLIST', '/FO', 'CSV')).decode()
# get rid of extra " and split into lines
output = output.replace('"', '').split('\r\n')
keys = output[0].split(',')
proc_list = [i.split(',') for i in output[1:] if i]
# make dict with proc names as keys and dicts with the extra nfo as values
proc_dict = dict((i[0], dict(zip(keys[1:], i[1:]))) for i in proc_list)
for name, values in sorted(proc_dict.items(), key=lambda x: x[0].lower()):
    print('%s: %s' % (name, values))
4 với một tiêu đề hoặc tên lớp đã biết.

def iTunesRunning():
    import win32ui
    # may need FindWindow("iTunes", None) or FindWindow(None, "iTunes")
    # or something similar
    if FindWindow("iTunes", "iTunes"):
        print "Found an iTunes window"
        return True

Đã trả lời ngày 16 tháng 10 năm 2011 lúc 21:09Oct 16, 2011 at 21:09

GabegabeGabe

83.6K12 Huy hiệu vàng136 Huy hiệu bạc233 Huy hiệu Đồng12 gold badges136 silver badges233 bronze badges

9

Tôi muốn thêm giải pháp này vào danh sách, cho các mục đích lịch sử. Nó cho phép bạn tìm hiểu dựa trên .exe thay vì tiêu đề cửa sổ và cũng trả về bộ nhớ được sử dụng & PID.

processes = subprocess.Popen('tasklist', stdin=subprocess.PIPE, stderr=subprocess.PIPE, stdout=subprocess.PIPE).communicate()[0]
# Put a regex for exact matches, or a simple 'in' for naive matches

Một lát đầu ra ví dụ:

notepad.exe                  13944 Console                    1     11,920 K
python.exe                    5240 Console                    1     28,616 K
conhost.exe                   9796 Console                    1      7,812 K
svchost.exe                   1052 Services                   0     18,524 K
iTunes.exe                    1108 Console                    1    157,764 K

Đã trả lời ngày 31 tháng 12 năm 2016 lúc 16:17Dec 31, 2016 at 16:17

import psutil

for p in psutil.process_iter(attrs=['pid', 'name']):
    if "itunes.exe" in (p.info['name']).lower():
        print("yes", (p.info['name']).lower())

cho Python 3.7


import psutil

for p in psutil.process_iter(attrs=['pid', 'name']):
    if p.info['name'] == "itunes.exe":
        print("yes", (p.info['name']))

Điều này hoạt động cho Python 3.8 & psutil 5.7.0, Windows

Đã trả lời ngày 30 tháng 8 năm 2019 lúc 0:33Aug 30, 2019 at 0:33

Hướng dẫn python check process running - quá trình kiểm tra python đang chạy

0m3r0m3r0m3r

11.8K15 Huy hiệu vàng31 Huy hiệu bạc69 Huy hiệu đồng15 gold badges31 silver badges69 bronze badges

Thử mã này:

import subprocess

def process_exists(process_name):
    call = 'TASKLIST', '/FI', 'imagename eq %s' % process_name
    # use buildin check_output right away
    output = subprocess.check_output(call).decode()
    # check in last line for process name
    last_line = output.strip().split('\r\n')[-1]
    # because Fail message could be translated
    return last_line.lower().startswith(process_name.lower())
0

Và để kiểm tra xem quá trình có đang chạy không:

import subprocess

def process_exists(process_name):
    call = 'TASKLIST', '/FI', 'imagename eq %s' % process_name
    # use buildin check_output right away
    output = subprocess.check_output(call).decode()
    # check in last line for process name
    last_line = output.strip().split('\r\n')[-1]
    # because Fail message could be translated
    return last_line.lower().startswith(process_name.lower())
1

Đã trả lời ngày 6 tháng 11 năm 2020 lúc 2:07Nov 6, 2020 at 2:07

mg34mg34mg34

Phù hiệu bằng đồng 3122 bronze badges

Bạn có hài lòng với lệnh Python của bạn chạy một chương trình khác để có được thông tin không?

Nếu vậy, tôi khuyên bạn nên xem PSList và tất cả các tùy chọn của nó. Ví dụ: những điều sau đây sẽ cho bạn biết về bất kỳ quy trình iTunes đang chạy nào

import subprocess

def process_exists(process_name):
    call = 'TASKLIST', '/FI', 'imagename eq %s' % process_name
    # use buildin check_output right away
    output = subprocess.check_output(call).decode()
    # check in last line for process name
    last_line = output.strip().split('\r\n')[-1]
    # because Fail message could be translated
    return last_line.lower().startswith(process_name.lower())
2

Nếu bạn có thể tìm ra cách giải thích kết quả, điều này hy vọng sẽ giúp bạn đi.

Edit:

Khi tôi không chạy iTunes, tôi sẽ nhận được như sau:

import subprocess

def process_exists(process_name):
    call = 'TASKLIST', '/FI', 'imagename eq %s' % process_name
    # use buildin check_output right away
    output = subprocess.check_output(call).decode()
    # check in last line for process name
    last_line = output.strip().split('\r\n')[-1]
    # because Fail message could be translated
    return last_line.lower().startswith(process_name.lower())
3

Với iTunes đang chạy, tôi nhận được một dòng bổ sung này:

import subprocess

def process_exists(process_name):
    call = 'TASKLIST', '/FI', 'imagename eq %s' % process_name
    # use buildin check_output right away
    output = subprocess.check_output(call).decode()
    # check in last line for process name
    last_line = output.strip().split('\r\n')[-1]
    # because Fail message could be translated
    return last_line.lower().startswith(process_name.lower())
4

Tuy nhiên, lệnh sau đây chỉ in thông tin về chính chương trình iTunes, tức là với đối số

# get info dict about all running processes
import subprocess
output = subprocess.check_output(('TASKLIST', '/FO', 'CSV')).decode()
# get rid of extra " and split into lines
output = output.replace('"', '').split('\r\n')
keys = output[0].split(',')
proc_list = [i.split(',') for i in output[1:] if i]
# make dict with proc names as keys and dicts with the extra nfo as values
proc_dict = dict((i[0], dict(zip(keys[1:], i[1:]))) for i in proc_list)
for name, values in sorted(proc_dict.items(), key=lambda x: x[0].lower()):
    print('%s: %s' % (name, values))
5:

import subprocess

def process_exists(process_name):
    call = 'TASKLIST', '/FI', 'imagename eq %s' % process_name
    # use buildin check_output right away
    output = subprocess.check_output(call).decode()
    # check in last line for process name
    last_line = output.strip().split('\r\n')[-1]
    # because Fail message could be translated
    return last_line.lower().startswith(process_name.lower())
5

Đã trả lời ngày 16 tháng 10 năm 2011 lúc 20:41Oct 16, 2011 at 20:41

Clare MacRaeclare MacRaeClare Macrae

3.5722 Huy hiệu vàng28 Huy hiệu bạc44 Huy hiệu đồng2 gold badges28 silver badges44 bronze badges

5

Nếu không thể dựa vào tên quy trình như các tập lệnh Python sẽ luôn có python.exe dưới dạng tên quy trình. Nếu tìm thấy phương pháp này rất tiện dụng

import subprocess

def process_exists(process_name):
    call = 'TASKLIST', '/FI', 'imagename eq %s' % process_name
    # use buildin check_output right away
    output = subprocess.check_output(call).decode()
    # check in last line for process name
    last_line = output.strip().split('\r\n')[-1]
    # because Fail message could be translated
    return last_line.lower().startswith(process_name.lower())
6

Kiểm tra tài liệu để biết thêm thông tin http://psutil.readthedocs.io/en/latest/#psutil.pid_exists

Đã trả lời ngày 17 tháng 12 năm 2017 lúc 16:41Dec 17, 2017 at 16:41

AkramakramAkram

4134 Huy hiệu bạc19 Huy hiệu đồng4 silver badges19 bronze badges

Có một mô -đun Python gọi là WMI.

import subprocess

def process_exists(process_name):
    call = 'TASKLIST', '/FI', 'imagename eq %s' % process_name
    # use buildin check_output right away
    output = subprocess.check_output(call).decode()
    # check in last line for process name
    last_line = output.strip().split('\r\n')[-1]
    # because Fail message could be translated
    return last_line.lower().startswith(process_name.lower())
7

Đã trả lời ngày 9 tháng 9 năm 2020 lúc 3:48Sep 9, 2020 at 3:48

Hướng dẫn python check process running - quá trình kiểm tra python đang chạy

Theo bài đăng của Ewerybody: https://stackoverflow.com/a/29275361/7530957

Nhiều vấn đề có thể phát sinh:

  • Nhiều quy trình có cùng tên
  • Tên của quá trình dài

Mã 'Ewerybody' sẽ không hoạt động nếu tên quy trình dài. Vì vậy, có một vấn đề với dòng này:

import subprocess

def process_exists(process_name):
    call = 'TASKLIST', '/FI', 'imagename eq %s' % process_name
    # use buildin check_output right away
    output = subprocess.check_output(call).decode()
    # check in last line for process name
    last_line = output.strip().split('\r\n')[-1]
    # because Fail message could be translated
    return last_line.lower().startswith(process_name.lower())
8

Bởi vì Last_line sẽ ngắn hơn tên quy trình.

Vì vậy, nếu bạn chỉ muốn biết nếu một quy trình/quy trình đang hoạt động:

import subprocess

def process_exists(process_name):
    call = 'TASKLIST', '/FI', 'imagename eq %s' % process_name
    # use buildin check_output right away
    output = subprocess.check_output(call).decode()
    # check in last line for process name
    last_line = output.strip().split('\r\n')[-1]
    # because Fail message could be translated
    return last_line.lower().startswith(process_name.lower())
9

Thay vào đó cho tất cả các thông tin của một quy trình/quy trình

>>> process_exists('eclipse.exe')
True

>>> process_exists('AJKGVSJGSCSeclipse.exe')
False
0

Đã trả lời ngày 29 tháng 5 năm 2020 lúc 11:06May 29, 2020 at 11:06

SqualosqualoSqualo

7910 Huy hiệu đồng10 bronze badges

1

Phương pháp này dưới đây có thể được sử dụng để phát hiện thời tiết quá trình [ví dụ: notepad.exe] đang chạy hay không.

>>> process_exists('eclipse.exe')
True

>>> process_exists('AJKGVSJGSCSeclipse.exe')
False
1

Gói Pymem là cần thiết.Để cài đặt nó,

>>> process_exists('eclipse.exe')
True

>>> process_exists('AJKGVSJGSCSeclipse.exe')
False
2

Đã trả lời ngày 16 tháng 2 năm 2021 lúc 8:59Feb 16, 2021 at 8:59

Điều này hoạt động độc đáo

>>> process_exists('eclipse.exe')
True

>>> process_exists('AJKGVSJGSCSeclipse.exe')
False
3

Đã trả lời ngày 13 tháng 4 năm 2016 lúc 21:55Apr 13, 2016 at 21:55

Nếu bạn đang thử nghiệm ứng dụng với cư xử, bạn có thể sử dụng

# get info dict about all running processes
import subprocess
output = subprocess.check_output(('TASKLIST', '/FO', 'CSV')).decode()
# get rid of extra " and split into lines
output = output.replace('"', '').split('\r\n')
keys = output[0].split(',')
proc_list = [i.split(',') for i in output[1:] if i]
# make dict with proc names as keys and dicts with the extra nfo as values
proc_dict = dict((i[0], dict(zip(keys[1:], i[1:]))) for i in proc_list)
for name, values in sorted(proc_dict.items(), key=lambda x: x[0].lower()):
    print('%s: %s' % (name, values))
6.Tương tự với nhận xét trước đây, bạn có thể sử dụng chức năng này:

>>> process_exists('eclipse.exe')
True

>>> process_exists('AJKGVSJGSCSeclipse.exe')
False
4

# get info dict about all running processes
import subprocess
output = subprocess.check_output(('TASKLIST', '/FO', 'CSV')).decode()
# get rid of extra " and split into lines
output = output.replace('"', '').split('\r\n')
keys = output[0].split(',')
proc_list = [i.split(',') for i in output[1:] if i]
# make dict with proc names as keys and dicts with the extra nfo as values
proc_dict = dict((i[0], dict(zip(keys[1:], i[1:]))) for i in proc_list)
for name, values in sorted(proc_dict.items(), key=lambda x: x[0].lower()):
    print('%s: %s' % (name, values))
7 có thể là 'uia' hoặc 'win32'

# get info dict about all running processes
import subprocess
output = subprocess.check_output(('TASKLIST', '/FO', 'CSV')).decode()
# get rid of extra " and split into lines
output = output.replace('"', '').split('\r\n')
keys = output[0].split(',')
proc_list = [i.split(',') for i in output[1:] if i]
# make dict with proc names as keys and dicts with the extra nfo as values
proc_dict = dict((i[0], dict(zip(keys[1:], i[1:]))) for i in proc_list)
for name, values in sorted(proc_dict.items(), key=lambda x: x[0].lower()):
    print('%s: %s' % (name, values))
8 Nếu để kết nối lại lực với ứng dụng trong 5 giây.

Đã trả lời ngày 11 tháng 9 năm 2019 lúc 14:34Sep 11, 2019 at 14:34

>>> process_exists('eclipse.exe')
True

>>> process_exists('AJKGVSJGSCSeclipse.exe')
False
5

Đã trả lời ngày 16 tháng 10 năm 2019 lúc 16:06Oct 16, 2019 at 16:06

Hướng dẫn python check process running - quá trình kiểm tra python đang chạy

>>> process_exists('eclipse.exe')
True

>>> process_exists('AJKGVSJGSCSeclipse.exe')
False
6

Đã trả lời ngày 24 tháng 4 năm 2020 lúc 12:43Apr 24, 2020 at 12:43

Hướng dẫn python check process running - quá trình kiểm tra python đang chạy

Viraj Wadateviraj WadateViraj Wadate

4.6791 Huy hiệu vàng27 Huy hiệu bạc28 Huy hiệu đồng1 gold badge27 silver badges28 bronze badges

# get info dict about all running processes
import subprocess
output = subprocess.check_output(('TASKLIST', '/FO', 'CSV')).decode()
# get rid of extra " and split into lines
output = output.replace('"', '').split('\r\n')
keys = output[0].split(',')
proc_list = [i.split(',') for i in output[1:] if i]
# make dict with proc names as keys and dicts with the extra nfo as values
proc_dict = dict((i[0], dict(zip(keys[1:], i[1:]))) for i in proc_list)
for name, values in sorted(proc_dict.items(), key=lambda x: x[0].lower()):
    print('%s: %s' % (name, values))
9 là giải pháp tốt nhất cho việc này.

>>> process_exists('eclipse.exe')
True

>>> process_exists('AJKGVSJGSCSeclipse.exe')
False
7

Đã trả lời ngày 9 tháng 2 năm 2021 lúc 12:21Feb 9, 2021 at 12:21

VoldemortVoldEmortVoldemort

2533 Huy hiệu bạc16 Huy hiệu Đồng3 silver badges16 bronze badges

Bạn chỉ có thể sử dụng

import win32ui

def WindowExists(classname):
    try:
        win32ui.FindWindow(classname, None)
    except win32ui.error:
        return False
    else:
        return True

if WindowExists("DropboxTrayIcon"):
    print "Dropbox is running, sir."
else:
    print "Dropbox is running..... not."
0 gửi tín hiệu 0 (không giết chết quy trình) và kiểm tra lỗi.

>>> process_exists('eclipse.exe')
True

>>> process_exists('AJKGVSJGSCSeclipse.exe')
False
8

Đã trả lời ngày 3 tháng 7 năm 2021 lúc 17:37Jul 3, 2021 at 17:37

Hướng dẫn python check process running - quá trình kiểm tra python đang chạy

Thalescrthalescrthalescr

Huy hiệu bạc 1011 Huy hiệu đồng1 silver badge4 bronze badges

Tôi thích giải pháp của @Awerybody với sự thay đổi nhỏ này

>>> process_exists('eclipse.exe')
True

>>> process_exists('AJKGVSJGSCSeclipse.exe')
False
9

Đã trả lời ngày 13 tháng 2 lúc 6:25Feb 13 at 6:25