У меня была такая же проблема. Они приняли его после того, как я сменил индивидуальный членский счет на членство в компании / организации и amp; снова загрузил его. Если ваш товар является зарегистрированным брендом, он должен быть учетной записью компании, которая отражает фирменное наименование вашего продукта
Библиотека psutil предоставит вам некоторую системную информацию (использование ЦП / памяти) на различных платформах:
psutil - это модуль, обеспечивающий интерфейс для извлечения информацию о запущенных процессах и использовании системы (CPU, memory) в переносном режиме с помощью Python, реализуя множество функций, предлагаемых такими инструментами, как ps, top и диспетчер задач Windows.
В настоящее время он поддерживает Linux, Windows, OSX , Sun Solaris, FreeBSD, OpenBSD и NetBSD, как 32-разрядные, так и 64-разрядные архитектуры с версиями Python от 2.6 до 3.5 (пользователи Python 2.4 и 2.5 могут использовать версию 2.1.3).
Мне кажется, что эти ответы были написаны для Python 2, и в любом случае никто не упомянул стандартный пакет resource
, доступный для Python 3. Он предоставляет команды для получения ресурса ограничивает данного процесса (по умолчанию процесс вызова Python). Это не то же самое, что получение текущего использования ресурсов системой в целом, но оно может решить некоторые из тех же проблем, как например. «Я хочу убедиться, что я использую только X много оперативной памяти с этим скриптом».
Ниже кодов без внешних библиотек работали для меня. Я тестировал в Python 2.7.9
Использование ЦП
import os
CPU_Pct=str(round(float(os.popen('''grep 'cpu ' /proc/stat | awk '{usage=($2+$4)*100/($2+$4+$5)} END {print usage }' ''').readline()),2))
#print results
print("CPU Usage = " + CPU_Pct)
И использование Ram, Total, Used и Free
import os
mem=str(os.popen('free -t -m').readlines())
"""
Get a whole line of memory output, it will be something like below
[' total used free shared buffers cached\n',
'Mem: 925 591 334 14 30 355\n',
'-/+ buffers/cache: 205 719\n',
'Swap: 99 0 99\n',
'Total: 1025 591 434\n']
So, we need total memory, usage and free memory.
We should find the index of capital T which is unique at this string
"""
T_ind=mem.index('T')
"""
Than, we can recreate the string with this information. After T we have,
"Total: " which has 14 characters, so we can start from index of T +14
and last 4 characters are also not necessary.
We can create a new sub-string using this information
"""
mem_G=mem[T_ind+14:-4]
"""
The result will be like
1025 603 422
we need to find first index of the first space, and we can start our substring
from from 0 to this index number, this will give us the string of total memory
"""
S1_ind=mem_G.index(' ')
mem_T=mem_G[0:S1_ind]
"""
Similarly we will create a new sub-string, which will start at the second value.
The resulting string will be like
603 422
Again, we should find the index of first space and than the
take the Used Memory and Free memory.
"""
mem_G1=mem_G[S1_ind+8:]
S2_ind=mem_G1.index(' ')
mem_U=mem_G1[0:S2_ind]
mem_F=mem_G1[S2_ind+8:]
print 'Summary = ' + mem_G
print 'Total Memory = ' + mem_T +' MB'
print 'Used Memory = ' + mem_U +' MB'
print 'Free Memory = ' + mem_F +' MB'
Используйте библиотеку psutil . Для меня на Ubuntu, pip установлен 0.4.3. Вы можете проверить свою версию psutil, выполнив
from __future__ import print_function
import psutil
print(psutil.__version__)
в Python.
Чтобы получить некоторую память и статистику процессора:
from __future__ import print_function
import psutil
print(psutil.cpu_percent())
print(psutil.virtual_memory()) # physical memory usage
Мне также нравится для выполнения:
import os
import psutil
pid = os.getpid()
py = psutil.Process(pid)
memoryUse = py.memory_info()[0]/2.**30 # memory use in GB...I think
print('memory use:', memoryUse)
, который дает текущее использование памяти вашего скрипта Python.
Есть более подробные примеры на странице pypi для 4.3.0 и 0.5.0 .
Для Ubuntu 16 и 14, установка из pip дала мне версию 4.3.0, которая не имеет метода phymem_usage (). Чтобы получить 0.5.0, загрузите файл tar.gz , затем выполните
tar -xvzf psutil-0.5.0.tar.gz
cd psutil-0.5.0
sudo python setup.py install
Один слой для использования ОЗУ с только зависимостью stdlib:
import os
tot_m, used_m, free_m = map(int, os.popen('free -t -m').readlines()[-1].split()[1:])
Вы можете использовать psutil или psmem с кодом примера подпроцесса
import subprocess
cmd = subprocess.Popen(['sudo','./ps_mem'],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
out,error = cmd.communicate()
memory = out.splitlines()
Ссылка http://techarena51.com/index.php/how-to-install-python-3-and -flask-on-linux /
Вот что-то, что я собрал некоторое время назад, это только окна, но может помочь вам получить часть того, что вам нужно.
Производится из: «для sys available mem» http: // msdn2.microsoft.com/en-us/library/aa455130.aspx
"отдельные данные процесса и примеры сценариев python" http://www.microsoft.com/technet/ scriptcenter / scripts / default.mspx? mfr = true
ПРИМЕЧАНИЕ: интерфейс / процесс WMI также доступен для выполнения аналогичных задач. Я не использую его здесь, потому что текущий метод покрывает мои потребности , но если когда-нибудь это потребуется, чтобы расширить или улучшить это, тогда может понадобиться изучить возможности WMI-инструментов.
WMI для python:
http: // tgolden. sc.sabren.com/python/wmi.html
Код:
'''
Monitor window processes
derived from:
>for sys available mem
http://msdn2.microsoft.com/en-us/library/aa455130.aspx
> individual process information and python script examples
http://www.microsoft.com/technet/scriptcenter/scripts/default.mspx?mfr=true
NOTE: the WMI interface/process is also available for performing similar tasks
I'm not using it here because the current method covers my needs, but if someday it's needed
to extend or improve this module, then may want to investigate the WMI tools available.
WMI for python:
http://tgolden.sc.sabren.com/python/wmi.html
'''
__revision__ = 3
import win32com.client
from ctypes import *
from ctypes.wintypes import *
import pythoncom
import pywintypes
import datetime
class MEMORYSTATUS(Structure):
_fields_ = [
('dwLength', DWORD),
('dwMemoryLoad', DWORD),
('dwTotalPhys', DWORD),
('dwAvailPhys', DWORD),
('dwTotalPageFile', DWORD),
('dwAvailPageFile', DWORD),
('dwTotalVirtual', DWORD),
('dwAvailVirtual', DWORD),
]
def winmem():
x = MEMORYSTATUS() # create the structure
windll.kernel32.GlobalMemoryStatus(byref(x)) # from cytypes.wintypes
return x
class process_stats:
'''process_stats is able to provide counters of (all?) the items available in perfmon.
Refer to the self.supported_types keys for the currently supported 'Performance Objects'
To add logging support for other data you can derive the necessary data from perfmon:
---------
perfmon can be run from windows 'run' menu by entering 'perfmon' and enter.
Clicking on the '+' will open the 'add counters' menu,
From the 'Add Counters' dialog, the 'Performance object' is the self.support_types key.
--> Where spaces are removed and symbols are entered as text (Ex. # == Number, % == Percent)
For the items you wish to log add the proper attribute name in the list in the self.supported_types dictionary,
keyed by the 'Performance Object' name as mentioned above.
---------
NOTE: The 'NETFramework_NETCLRMemory' key does not seem to log dotnet 2.0 properly.
Initially the python implementation was derived from:
http://www.microsoft.com/technet/scriptcenter/scripts/default.mspx?mfr=true
'''
def __init__(self,process_name_list=[],perf_object_list=[],filter_list=[]):
'''process_names_list == the list of all processes to log (if empty log all)
perf_object_list == list of process counters to log
filter_list == list of text to filter
print_results == boolean, output to stdout
'''
pythoncom.CoInitialize() # Needed when run by the same process in a thread
self.process_name_list = process_name_list
self.perf_object_list = perf_object_list
self.filter_list = filter_list
self.win32_perf_base = 'Win32_PerfFormattedData_'
# Define new datatypes here!
self.supported_types = {
'NETFramework_NETCLRMemory': [
'Name',
'NumberTotalCommittedBytes',
'NumberTotalReservedBytes',
'NumberInducedGC',
'NumberGen0Collections',
'NumberGen1Collections',
'NumberGen2Collections',
'PromotedMemoryFromGen0',
'PromotedMemoryFromGen1',
'PercentTimeInGC',
'LargeObjectHeapSize'
],
'PerfProc_Process': [
'Name',
'PrivateBytes',
'ElapsedTime',
'IDProcess',# pid
'Caption',
'CreatingProcessID',
'Description',
'IODataBytesPersec',
'IODataOperationsPersec',
'IOOtherBytesPersec',
'IOOtherOperationsPersec',
'IOReadBytesPersec',
'IOReadOperationsPersec',
'IOWriteBytesPersec',
'IOWriteOperationsPersec'
]
}
def get_pid_stats(self, pid):
this_proc_dict = {}
pythoncom.CoInitialize() # Needed when run by the same process in a thread
if not self.perf_object_list:
perf_object_list = self.supported_types.keys()
for counter_type in perf_object_list:
strComputer = "."
objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator")
objSWbemServices = objWMIService.ConnectServer(strComputer,"root\cimv2")
query_str = '''Select * from %s%s''' % (self.win32_perf_base,counter_type)
colItems = objSWbemServices.ExecQuery(query_str) # "Select * from Win32_PerfFormattedData_PerfProc_Process")# changed from Win32_Thread
if len(colItems) > 0:
for objItem in colItems:
if hasattr(objItem, 'IDProcess') and pid == objItem.IDProcess:
for attribute in self.supported_types[counter_type]:
eval_str = 'objItem.%s' % (attribute)
this_proc_dict[attribute] = eval(eval_str)
this_proc_dict['TimeStamp'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.') + str(datetime.datetime.now().microsecond)[:3]
break
return this_proc_dict
def get_stats(self):
'''
Show process stats for all processes in given list, if none given return all processes
If filter list is defined return only the items that match or contained in the list
Returns a list of result dictionaries
'''
pythoncom.CoInitialize() # Needed when run by the same process in a thread
proc_results_list = []
if not self.perf_object_list:
perf_object_list = self.supported_types.keys()
for counter_type in perf_object_list:
strComputer = "."
objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator")
objSWbemServices = objWMIService.ConnectServer(strComputer,"root\cimv2")
query_str = '''Select * from %s%s''' % (self.win32_perf_base,counter_type)
colItems = objSWbemServices.ExecQuery(query_str) # "Select * from Win32_PerfFormattedData_PerfProc_Process")# changed from Win32_Thread
try:
if len(colItems) > 0:
for objItem in colItems:
found_flag = False
this_proc_dict = {}
if not self.process_name_list:
found_flag = True
else:
# Check if process name is in the process name list, allow print if it is
for proc_name in self.process_name_list:
obj_name = objItem.Name
if proc_name.lower() in obj_name.lower(): # will log if contains name
found_flag = True
break
if found_flag:
for attribute in self.supported_types[counter_type]:
eval_str = 'objItem.%s' % (attribute)
this_proc_dict[attribute] = eval(eval_str)
this_proc_dict['TimeStamp'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.') + str(datetime.datetime.now().microsecond)[:3]
proc_results_list.append(this_proc_dict)
except pywintypes.com_error, err_msg:
# Ignore and continue (proc_mem_logger calls this function once per second)
continue
return proc_results_list
def get_sys_stats():
''' Returns a dictionary of the system stats'''
pythoncom.CoInitialize() # Needed when run by the same process in a thread
x = winmem()
sys_dict = {
'dwAvailPhys': x.dwAvailPhys,
'dwAvailVirtual':x.dwAvailVirtual
}
return sys_dict
if __name__ == '__main__':
# This area used for testing only
sys_dict = get_sys_stats()
stats_processor = process_stats(process_name_list=['process2watch'],perf_object_list=[],filter_list=[])
proc_results = stats_processor.get_stats()
for result_dict in proc_results:
print result_dict
import os
this_pid = os.getpid()
this_proc_results = stats_processor.get_pid_stats(this_pid)
print 'this proc results:'
print this_proc_results
http://monkut.webfactional.com/blog/ Архив / 2009 / 1/21 / окна-процесс-память каротаж питон
from x import *
! Они загромождают основное пространство имен и перезаписывают другие функции и переменные.
– phobie
25 September 2012 в 19:33
"... текущий статус системы (текущий процессор, оперативная память, свободное место на диске и т. д.). И« * nix и платформы Windows »могут быть сложной комбинацией.
Операционные системы в корне отличаются тем, как они управляют этими ресурсами. Действительно, они отличаются основными понятиями, такими как определение того, что считается системой, и что считается временем приложения.
«Свободное дисковое пространство»? Что считается «дисковым пространством»? Все разделы всех устройств? Что касается иностранных разделов в многозагрузочной среде?
Не думаю, что между Windows и * nix существует достаточно четкое согласие, которое делает это возможным. В самом деле, между различными операционными системами под Windows не может быть никакого консенсуса. Существует ли один API Windows, который работает как для XP, так и для Vista?
df -h
отвечает на «дисковое пространство». вопрос как на Windows, так и на * nix.
– jfs
10 November 2008 в 21:44
Я не верю, что имеется хорошо поддерживаемая многоплатформенная библиотека. Помните, что сам Python написан на C, поэтому любая библиотека просто собирается принять разумное решение о том, какой фрагмент кода для операционной системы будет запущен, как вы сказали выше.
$ pip install psutil
;>>> import psutil; psutil.cpu_percent()
и>>> psutil.virtual_memory()
, которые возвращают хороший объект vmem:vmem(total=8589934592L, available=4073336832L, percent=52.6, used=5022085120L, free=3560255488L, active=2817949696L, inactive=513081344L, wired=1691054080L)
– hobs 17 May 2013 в 18:28tar -xvzf psutil-0.5.0.tar.gz
, затемcd psutil-0.5.0
, затемsudo python setup.py install
. Вы можете проверить свою версию psutil, выполнивimport psutil
иprint(psutil.__version__)
в python – wordsforthewise 16 August 2016 в 20:52