def test_getallocatedblocks(self): # Some sanity checks with_pymalloc = sysconfig.get_config_var('WITH_PYMALLOC') a = sys.getallocatedblocks() self.assertIs(type(a), int) if with_pymalloc: self.assertGreater(a, 0) else: # When WITH_PYMALLOC isn't available, we don't know anything # about the underlying implementation: the function might # return 0 or something greater. self.assertGreaterEqual(a, 0) try: # While we could imagine a Python session where the number of # multiple buffer objects would exceed the sharing of references, # it is unlikely to happen in a normal test run. self.assertLess(a, sys.gettotalrefcount()) except AttributeError: # gettotalrefcount() not available pass gc.collect() b = sys.getallocatedblocks() self.assertLessEqual(b, a) gc.collect() c = sys.getallocatedblocks() self.assertIn(c, range(b - 50, b + 50))
def _run_test(self, work_func: FunctionType, work_resource: object, jobs: int, trials: int, show_progress: bool = False) -> Mapping: results = { 'jobs': jobs, 'trials': trials, 'time': [], 'blocks': [], } # Forcibly evaluate the inputs to prevent time/resources taken up later inputs = list(zip([work_resource] * jobs, range(jobs))) trial_iter = range(trials) if show_progress is True and trials > 2: trial_iter = tqdm(trial_iter, desc='trials') gc.collect() for _ in trial_iter: # Run trial of pool map function and measure it gc.collect() blocks_start = sys.getallocatedblocks() time_start = time.time() list(self.map(work_func, inputs)) time_end = time.time() results['time'].append(time_end - time_start) # Get allocated blocks before garbage collection to show peak usage blocks_end = sys.getallocatedblocks() results['blocks'].append(blocks_end - blocks_start) return results
def sms_reply(): """Respond to incoming calls. This is the entrypoint for SpeedTrivia functionality. """ # log this number to track memory useage and monitor for memory leaks. # TODO take a timestamp snapshot here memory_footprint = sys.getallocatedblocks() logger.debug(f"Running program footprint is: {memory_footprint}") logger.info("Message received:") # recover SMS details from Twillio. This functionality is magic. sms_body = request.values.get("Body", None) sms_from = request.values.get("From", None) sms_MSID = request.values.get("MessageSid", None) logger.info(sms_MSID) logger.info(sms_from) logger.info(sms_body) # Generate an appropriate response (if any) if (sms_body == None) or (sms_from == None) or (sms_MSID == None): logger.error( f'Invalid SMS recieved. "None" value encountered.') reply = "Unknown system error. SMS is invalid." else: reply = Respond_to(sms_MSID, sms_from, sms_body) if reply == "": logger.info("No response needed.") reply = "Thank you." elif reply == None: logger.error(f'Respond_to function returned "None".') reply = "Unknown system error. Please try again." Send_SMS(reply, sms_from) logger.info("Updating database...") pickle.dump(players_database, open(DATABASE_PATHOBJ, "wb")) logger.info("Returning control to Flask.") # TODO take another time snapshot and log the time elapsed. return reply
def __init__(self): print('looking at some sys functions') print(sys.api_version) print(sys.argv) print(sys.base_exec_prefix) print(sys.base_prefix) print(sys.builtin_module_names) print(sys.byteorder) print(sys.copyright) print(sys.dllhandle) print(sys.exc_info()) # print(sys.exc_traceback) print(sys.executable) print(sys.path) print(sys.maxsize) print(sys.platform) print(sys.flags) print(sys.float_info) print(sys.float_repr_style) print(sys._framework) print(sys.getdefaultencoding()) print(sys.getwindowsversion()) print(sys.getallocatedblocks()) print(sys.getfilesystemencodeerrors()) # print(sys.getcheckinterval()) print(sys.getprofile()) print(sys.getrecursionlimit()) print(sys.getswitchinterval()) print(sys.gettrace()) print(sys._git) print('\n') print(sys.getsizeof(self))
def new_function(*args, **kwargs): # print(f"{old_function.__name__}", end=" ") starting_memory = sys.getallocatedblocks() result = old_function(*args, **kwargs) print(f" - memory: " f"{sys.getallocatedblocks() - starting_memory} blocs") return result
def test_getallocatedblocks(self): with_pymalloc = sysconfig.get_config_var('WITH_PYMALLOC') a = sys.getallocatedblocks() self.assertIs(type(a), int) if with_pymalloc: self.assertGreater(a, 0) else: self.assertGreaterEqual(a, 0) try: self.assertLess(a, sys.gettotalrefcount()) except AttributeError: pass gc.collect() b = sys.getallocatedblocks() self.assertLessEqual(b, a) gc.collect() c = sys.getallocatedblocks() self.assertIn(c, range(b - 50, b + 50))
def index (self, **dummy_kwargs): """ return stats. """ stats = {} stats['sessions'] = len(RamSession.cache) stats['sessions_storage'] = deep_getsizeof(RamSession.cache, set()) stats['allocated_blocks'] = sys.getallocatedblocks() stats['rusage_self'] = resource.getrusage(resource.RUSAGE_SELF) stats['rusage_children'] = resource.getrusage(resource.RUSAGE_CHILDREN) stats['thread_info'] = thread_info() return stats
def test_getallocatedblocks(self): try: import _testcapi except ImportError: with_pymalloc = support.with_pymalloc() else: try: alloc_name = _testcapi.pymem_getallocatorsname() except RuntimeError as exc: # "cannot get allocators name" (ex: tracemalloc is used) with_pymalloc = True else: with_pymalloc = (alloc_name in ('pymalloc', 'pymalloc_debug')) # Some sanity checks a = sys.getallocatedblocks() self.assertIs(type(a), int) if with_pymalloc: self.assertGreater(a, 0) else: # When WITH_PYMALLOC isn't available, we don't know anything # about the underlying implementation: the function might # return 0 or something greater. self.assertGreaterEqual(a, 0) try: # While we could imagine a Python session where the number of # multiple buffer objects would exceed the sharing of references, # it is unlikely to happen in a normal test run. self.assertLess(a, sys.gettotalrefcount()) except AttributeError: # gettotalrefcount() not available pass gc.collect() b = sys.getallocatedblocks() self.assertLessEqual(b, a) gc.collect() c = sys.getallocatedblocks() self.assertIn(c, range(b - 50, b + 50))
def system_info() -> dict: return { 'os': { 'PID': os.getpid(), 'Name': os.name, 'uname': os.uname(), 'CPU_Count': os.cpu_count() }, 'sys': { 'implementation': sys.implementation, 'executable': sys.executable, 'allocated_blocks': sys.getallocatedblocks() } }
print(sys.exec_prefix) print(sys.executable) print(sys.flags) print(sys.float_info) print(sys.float_info.dig) s = '3.14159265358979' # decimal string with 15 significant digits print(format(float(s), '.15g')) # convert to float and back -> same value s = '9876543211234567' # 16 significant digits is too many! print(format(float(s), '.16g')) # conversion changes value print(sys.float_repr_style) # 返回解释器当前分配的内存块数,而不考虑其大小。 print(sys.getallocatedblocks()) # 3.2版后已移除: Use getswitchinterval() instead. # setcheckinterval(). # print(sys.getcheckinterval()) # 返回解释器的“线程切换间隔。 print(sys.getswitchinterval()) # setswitchinterval(). print(sys.getdefaultencoding()) print(sys.getfilesystemencoding()) print(sys.getfilesystemencodeerrors()) # 返回<object>的引用次数。 # 引用次数会比期望值值多一个,因为它包含getrefcount()参数的临时引用。 class Test():
#setswitchinterval(n),在Python解释器中设置理想的线程切换延迟, #如果解释器执行长序列的不可中断代码(这是特定于实现的和依赖于工作负载的), #则切换线程的实际频率可能较低。 #该参数必须以秒为单位表示所需的切换延迟典型值为0.005(5毫秒)。 #set_coroutine_wrapper(wrapper),设置一个协程对象的装饰器 #set_asyncgen_hooks(*,firstiter=None,finalizer=None), #为异步生成器对象设置终结器。 #intern(string),python字符串的内存驻留机制, ''' python默认只会对由字符 "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz" 构成字符串进行intern。 由于有上面的限制,我们可以指定任意字符串使用intern机制,来减少内存占用 ''' #getallocatedblocks(),返回当前分配的内存块数量,而不管它们的大小。 print(sys.getallocatedblocks()) #getdefaultencoding(),返回Unicode实现使用的当前默认字符串编码。 print(sys.getdefaultencoding()) #getwindowsversion(),返回当前运行的windows版本的信息,以元组形式, print(sys.getwindowsversion()) #is_finalizing(),如果python已经退出则返回true sys.is_finalizing()
print(sys.base_exec_prefix) print(sys.base_prefix) print(sys.copyright) # Python interpreter copyright print(sys.executable) # Prints path to python binary executable # sys.exit() # Exits print(sys.flags) print(sys.float_info) # max / min num info ############################### print(sys.getallocatedblocks( )) # See memory blocks currently allocated. Good for debugging memory leaks t = [] for i in range(100000): t.append(i) print(sys.getallocatedblocks()) ############################### print(sys.getdefaultencoding()) # Deafult string encoding (utf-8) print(sys.getsizeof(float)) # Size of object in bytes print(sys.hash_info) print(sys.int_info
C:/Users/Name/Desktop C:\Users\Name\AppData\Local\Programs\Python\Python37\Lib\idlelib C:\Users\Name\AppData\Local\Programs\Python\Python37\python37.zip C:\Users\Name\AppData\Local\Programs\Python\Python37\DLLs C:\Users\Name\AppData\Local\Programs\Python\Python37\lib C:\Users\Name\AppData\Local\Programs\Python\Python37 C:\Users\Name\AppData\Local\Programs\Python\Python37\lib\site-packages C:\Users\Name\AppData\Local\Programs\Python\Python37\lib\site-packages\win32 C:\Users\Name\AppData\Local\Programs\Python\Python37\lib\site-packages\win32\lib C:\Users\Name\AppData\Local\Programs\Python\Python37\lib\site-packages\Pythonwin >>> sys.version '3.7.8 (tags/v3.7.8:4b47a5b6ba, Jun 28 2020, 08:53:46) [MSC v.1916 64 bit (AMD64)]' >>> sys.version_info sys.version_info(major=3, minor=7, micro=8, releaselevel='final', serial=0) >>> sys.getallocatedblocks() 75800 >>> #displayhook >>> 25+26 51 >>> x="Saketh" >>> def display(x): print("Codegnan") print(x) >>> x 'Saketh' >>> display(x) Codegnan Saketh
def respond_via(self, sock): facts = { 'os.name': os.name, 'os.getpid': os.getpid(), 'os.supports_bytes_environ': os.supports_bytes_environ, 'os.getcwd': os.getcwd(), 'os.cpu_count': os.cpu_count(), 'os.sep': os.sep, 'os.altsep': os.altsep, 'os.extsep': os.extsep, 'os.pathsep': os.pathsep, 'os.defpath': os.defpath, 'os.linesep': os.linesep, 'os.devnull': os.devnull, 'socket.gethostname': socket.gethostname(), 'socket.gethostbyaddr': socket.gethostbyaddr(socket.gethostname()), 'socket.has_ipv6': socket.has_ipv6, 'sys.argv': sys.argv, 'sys.base_exec_prefix': sys.base_exec_prefix, 'sys.base_prefix': sys.base_prefix, 'sys.byteorder': sys.byteorder, 'sys.builtin_module_names': sys.builtin_module_names, 'sys.exec_prefix': sys.exec_prefix, 'sys.executable': sys.executable, 'sys.flags': { 'debug': sys.flags.debug, 'inspect': sys.flags.inspect, 'interactive': sys.flags.interactive, 'optimize': sys.flags.optimize, 'dont_write_bytecode': sys.flags.dont_write_bytecode, 'no_user_site': sys.flags.no_user_site, 'no_site': sys.flags.no_site, 'ignore_environment': sys.flags.ignore_environment, 'verbose': sys.flags.verbose, 'bytes_warning': sys.flags.bytes_warning, 'quiet': sys.flags.quiet, 'hash_randomization': sys.flags.hash_randomization, }, 'sys.float_info': { 'epsilon': sys.float_info.epsilon, 'dig': sys.float_info.dig, 'mant_dig': sys.float_info.mant_dig, 'max': sys.float_info.max, 'max_exp': sys.float_info.max_exp, 'max_10_exp': sys.float_info.max_10_exp, 'min': sys.float_info.min, 'min_exp': sys.float_info.min_exp, 'min_10_exp': sys.float_info.min_10_exp, 'radix': sys.float_info.radix, 'rounds': sys.float_info.rounds, }, 'sys.getallocatedblocks': sys.getallocatedblocks(), 'sys.getdefaultencoding': sys.getdefaultencoding(), 'sys.getfilesystemencoding': sys.getfilesystemencoding(), 'sys.hash_info': { 'width': sys.hash_info.width, 'modulus': sys.hash_info.modulus, 'inf': sys.hash_info.inf, 'nan': sys.hash_info.nan, 'imag': sys.hash_info.imag, 'algorithm': sys.hash_info.algorithm, 'hash_bits': sys.hash_info.hash_bits, 'seed_bits': sys.hash_info.seed_bits, }, 'sys.hexversion': sys.hexversion, #'sys.long_info': sys.long_info, # deprecated in 3 'sys.implementation': { 'name': sys.implementation.name, 'version': { 'major': sys.implementation.version.major, 'minor': sys.implementation.version.minor, 'micro': sys.implementation.version.micro, 'releaselevel': sys.implementation.version.releaselevel, 'serial': sys.implementation.version.serial, }, 'hexversion': sys.implementation.hexversion, 'cache_tag': sys.implementation.cache_tag, }, 'sys.int_info': { 'bits_per_digit': sys.int_info.bits_per_digit, 'sizeof_digit': sys.int_info.sizeof_digit, }, #'sys.maxint': sys.maxint, # deprecated in 3 'sys.maxsize': sys.maxsize, 'sys.maxunicode': sys.maxunicode, 'sys.modules': list(sys.modules.keys()), 'sys.path': sys.path, 'sys.platform': sys.platform, 'sys.prefix': sys.prefix, 'sys.thread_info': { 'name': sys.thread_info.name, 'lock': sys.thread_info.lock, 'version': sys.thread_info.version, }, 'sys.version': sys.version, 'sys.api_version': sys.api_version, 'sys.version_info': { 'major': sys.version_info.major, 'minor': sys.version_info.minor, 'micro': sys.version_info.micro, 'releaselevel': sys.version_info.releaselevel, 'serial': sys.version_info.serial, }, } facts['os.environ'] = {k: v for (k, v) in os.environ.items()} # Availability: Windows if sys.platform.startswith('win') or sys.platform.startswith('cygwin'): facts['os.getlogin'] = os.getlogin() facts['os.getpid'] = os.getpid() facts['os.getppid'] = os.getppid() winver = sys.getwindowsversion() facts['sys.getwindowsversion'] = { 'major': winver.major, 'minor': winver.minor, 'build': winver.build, 'platform': winver.platform, 'service_pack': winver.service_pack, 'service_pack_minor': winver.service_pack_minor, 'service_pack_major': winver.service_pack_major, 'suite_mask': winver.suite_mask, 'product_type': winver.product_type, } facts['sys.dllhandle'] = sys.dllhandle # # Availability: Unix/POSIX # # we're assuming Unix == POSIX for this purpose # if sys.platform.startswith('linux') or sys.platform.startswith('freebsd') or sys.platform.startswith('darwin'): # facts['sys.abiflags'] = sys.abiflags # facts['os.getegid'] = os.getegid() # facts['os.geteuid'] = os.geteuid() # facts['os.getgid'] = os.getgid() # facts['os.getgroups'] = os.getgroups() # facts['os.getlogin'] = os.getlogin() # facts['os.getpgid'] = os.getpgid() # facts['os.getpgrp'] = os.getpgrp() # facts['os.getpid'] = os.getpid() # facts['os.getppid'] = os.getppid() # facts['os.getpriority'] = os.getpriority() # facts['os.getresuid'] = os.getresuid() # facts['os.getresgid'] = os.getresgid() # facts['os.getuid'] = os.getuid() # facts['os.getloadavg'] = os.getloadavg() # facts['os.uname'] = os.uname() # # facts['socket.if_nameindex'] = socket.if_nameindex() # facts['sys.getdlopenflags'] = sys.getdlopenflags() resp = FactsResponseMessage(facts) resp.send_via(sock)
def respond_via(self, sock): facts = { 'os.name': os.name, 'os.getpid': os.getpid(), 'os.supports_bytes_environ': os.supports_bytes_environ, 'os.getcwd': os.getcwd(), 'os.cpu_count': os.cpu_count(), 'os.sep': os.sep, 'os.altsep': os.altsep, 'os.extsep': os.extsep, 'os.pathsep': os.pathsep, 'os.defpath': os.defpath, 'os.linesep': os.linesep, 'os.devnull': os.devnull, 'socket.gethostname': socket.gethostname(), 'socket.gethostbyaddr': socket.gethostbyaddr(socket.gethostname()), 'socket.has_ipv6': socket.has_ipv6, 'sys.argv': sys.argv, 'sys.base_exec_prefix': sys.base_exec_prefix, 'sys.base_prefix': sys.base_prefix, 'sys.byteorder': sys.byteorder, 'sys.builtin_module_names': sys.builtin_module_names, 'sys.exec_prefix': sys.exec_prefix, 'sys.executable': sys.executable, 'sys.flags': { 'debug': sys.flags.debug, 'inspect': sys.flags.inspect, 'interactive': sys.flags.interactive, 'optimize': sys.flags.optimize, 'dont_write_bytecode': sys.flags.dont_write_bytecode, 'no_user_site': sys.flags.no_user_site, 'no_site': sys.flags.no_site, 'ignore_environment': sys.flags.ignore_environment, 'verbose': sys.flags.verbose, 'bytes_warning': sys.flags.bytes_warning, 'quiet': sys.flags.quiet, 'hash_randomization': sys.flags.hash_randomization, }, 'sys.float_info': { 'epsilon': sys.float_info.epsilon, 'dig': sys.float_info.dig, 'mant_dig': sys.float_info.mant_dig, 'max': sys.float_info.max, 'max_exp': sys.float_info.max_exp, 'max_10_exp': sys.float_info.max_10_exp, 'min': sys.float_info.min, 'min_exp': sys.float_info.min_exp, 'min_10_exp': sys.float_info.min_10_exp, 'radix': sys.float_info.radix, 'rounds': sys.float_info.rounds, }, 'sys.getallocatedblocks': sys.getallocatedblocks(), 'sys.getdefaultencoding': sys.getdefaultencoding(), 'sys.getfilesystemencoding': sys.getfilesystemencoding(), 'sys.hash_info': { 'width': sys.hash_info.width, 'modulus': sys.hash_info.modulus, 'inf': sys.hash_info.inf, 'nan': sys.hash_info.nan, 'imag': sys.hash_info.imag, 'algorithm': sys.hash_info.algorithm, 'hash_bits': sys.hash_info.hash_bits, 'seed_bits': sys.hash_info.seed_bits, }, 'sys.hexversion': sys.hexversion, #'sys.long_info': sys.long_info, # deprecated in 3 'sys.implementation': { 'name': sys.implementation.name, 'version': { 'major': sys.implementation.version.major, 'minor': sys.implementation.version.minor, 'micro': sys.implementation.version.micro, 'releaselevel': sys.implementation.version.releaselevel, 'serial': sys.implementation.version.serial, }, 'hexversion': sys.implementation.hexversion, 'cache_tag': sys.implementation.cache_tag, }, 'sys.int_info': { 'bits_per_digit': sys.int_info.bits_per_digit, 'sizeof_digit': sys.int_info.sizeof_digit, }, #'sys.maxint': sys.maxint, # deprecated in 3 'sys.maxsize': sys.maxsize, 'sys.maxunicode': sys.maxunicode, 'sys.modules': list(sys.modules.keys()), 'sys.path': sys.path, 'sys.platform': sys.platform, 'sys.prefix': sys.prefix, 'sys.thread_info': { 'name': sys.thread_info.name, 'lock': sys.thread_info.lock, 'version': sys.thread_info.version, }, 'sys.version': sys.version, 'sys.api_version': sys.api_version, 'sys.version_info': { 'major': sys.version_info.major, 'minor': sys.version_info.minor, 'micro': sys.version_info.micro, 'releaselevel': sys.version_info.releaselevel, 'serial': sys.version_info.serial, }, } facts['os.environ'] = {k: v for (k,v) in os.environ.items()} # Availability: Windows if sys.platform.startswith('win') or sys.platform.startswith('cygwin'): facts['os.getlogin'] = os.getlogin() facts['os.getpid'] = os.getpid() facts['os.getppid'] = os.getppid() winver = sys.getwindowsversion() facts['sys.getwindowsversion'] = { 'major': winver.major, 'minor': winver.minor, 'build': winver.build, 'platform': winver.platform, 'service_pack': winver.service_pack, 'service_pack_minor': winver.service_pack_minor, 'service_pack_major': winver.service_pack_major, 'suite_mask': winver.suite_mask, 'product_type': winver.product_type, } facts['sys.dllhandle'] = sys.dllhandle # # Availability: Unix/POSIX # # we're assuming Unix == POSIX for this purpose # if sys.platform.startswith('linux') or sys.platform.startswith('freebsd') or sys.platform.startswith('darwin'): # facts['sys.abiflags'] = sys.abiflags # facts['os.getegid'] = os.getegid() # facts['os.geteuid'] = os.geteuid() # facts['os.getgid'] = os.getgid() # facts['os.getgroups'] = os.getgroups() # facts['os.getlogin'] = os.getlogin() # facts['os.getpgid'] = os.getpgid() # facts['os.getpgrp'] = os.getpgrp() # facts['os.getpid'] = os.getpid() # facts['os.getppid'] = os.getppid() # facts['os.getpriority'] = os.getpriority() # facts['os.getresuid'] = os.getresuid() # facts['os.getresgid'] = os.getresgid() # facts['os.getuid'] = os.getuid() # facts['os.getloadavg'] = os.getloadavg() # facts['os.uname'] = os.uname() # # facts['socket.if_nameindex'] = socket.if_nameindex() # facts['sys.getdlopenflags'] = sys.getdlopenflags() resp = FactsResponseMessage(facts) resp.send_via(sock)
def listPythonSystem(): """! Function to list information about the installed Python system. @return: Dictionary of {attributes: values}. """ try: dllhandle = sys.dllhandle except AttributeError: dllhandle = "Not Defined" try: androidapilevel = sys.getandroidapilevel() except AttributeError: androidapilevel = "Not Defined" try: dlopenflags = sys.getdlopenflags() except AttributeError: dlopenflags = "Not Defined" try: windowsversion_major = sys.getwindowsversion().major except AttributeError: windowsversion_major = "Not Defined" try: windowsversion_minor = sys.getwindowsversion().minor except AttributeError: windowsversion_minor = "Not Defined" try: windowsversion_build = sys.getwindowsversion().build except AttributeError: windowsversion_build = "Not Defined" try: windowsversion_platform = sys.getwindowsversion().platform except AttributeError: windowsversion_platform = "Not Defined" try: service_pack = sys.getwindowsversion().service_pack if service_pack == '': service_pack = 'Not Specified' except AttributeError: service_pack = "Not Defined" try: winver = sys.winver except AttributeError: winver = "Not Defined" if sys.thread_info.lock == None: thread_info_lock = "Not Defined" else: thread_info_lock = sys.thread_info.lock if sys.thread_info.version == None: thread_info_version = "Not Defined" else: thread_info_version = sys.thread_info.version results = {"allocatedblocks": str(sys.getallocatedblocks()), "androidapilevel": str(androidapilevel), "api_version": str(sys.api_version), "base_exec_prefix": str(sys.base_exec_prefix), "base_prefix": str(sys.base_prefix), "byteorder": str(sys.byteorder), "builtin_module_names": ' | '.join(sys.builtin_module_names), "defaultencoding": str(sys.getdefaultencoding()), "dllhandle": str(dllhandle), "dlopenflags": str(dlopenflags), "exec_prefix": str(sys.exec_prefix), "executable": str(sys.executable), "filesystemencoding": str(sys.getfilesystemencoding()), "filesystemencodeerrors": str(sys.getfilesystemencodeerrors()), "flag_debug": str(sys.flags.debug), "flag_inspect": str(sys.flags.inspect), "flag_interactive": str(sys.flags.interactive), "flag_optimize": str(sys.flags.optimize), "flag_dont_write_bytecode": str(sys.flags.dont_write_bytecode), "flag_no_user_site": str(sys.flags.no_user_site), "flag_no_site": str(sys.flags.no_site), "flag_ignore_environment": str(sys.flags.ignore_environment), "flag_verbose": str(sys.flags.verbose), "flag_bytes_warning": str(sys.flags.bytes_warning), "flag_quiet": str(sys.flags.quiet), "flag_has_randomization": str(sys.flags.hash_randomization), "flag_isolated": str(sys.flags.isolated), "flag_dev_mode": str(sys.flags.dev_mode), "flag_utf8_mode": str(sys.flags.utf8_mode), "float_info_max": str(sys.float_info.max), "float_info_max_exp": str(sys.float_info.max_exp), "float_info_max_10_exp": str(sys.float_info.max_10_exp), "float_info_min": str(sys.float_info.min), "float_info_min_exp": str(sys.float_info.min_exp), "float_info_min_10_exp": str(sys.float_info.min_10_exp), "float_info_dig": str(sys.float_info.dig), "float_info_mant_dig": str(sys.float_info.mant_dig), "float_info_epsilon": str(sys.float_info.epsilon), "float_info_radix": str(sys.float_info.radix), "float_info_rounds": str(sys.float_info.rounds), "float_repr_style": str(sys.float_repr_style), "hash_info_width": str(sys.hash_info.width), "hash_info_modulus": str(sys.hash_info.modulus), "hash_info_inf": str(sys.hash_info.inf), "hash_info_nan": str(sys.hash_info.nan), "hash_info_imag": str(sys.hash_info.imag), "hash_info_algorithm": str(sys.hash_info.algorithm), "hash_info_hash_bits": str(sys.hash_info.hash_bits), "hash_info_seed_bits": str(sys.hash_info.seed_bits), "hash_info_cutoff": str(sys.hash_info.cutoff), "hexversion": str(sys.hexversion), "implementation_name": str(sys.implementation.name), "implementation_cache_tag": str(sys.implementation.cache_tag), "int_info_bits_per_digit": str(sys.int_info.bits_per_digit), "int_info_sizeof_digit": str(sys.int_info.sizeof_digit), "maxsize": str(sys.maxsize), "maxunicode": str(sys.maxunicode), "platform": str(sys.platform), "prefix": str(sys.prefix), "recursionlimit": str(sys.getrecursionlimit()), "switchinterval": str(sys.getswitchinterval()), "thread_info_name": str(sys.thread_info.name), "thread_info_lock": str(thread_info_lock), "thread_info_version": str(thread_info_version), "version_info_major": str(sys.version_info.major), "version_info_minor:": str(sys.version_info.minor), "version_info_micro": str(sys.version_info.micro), "version_info_releaselevel": str(sys.version_info.releaselevel), "version_info_serial": str(sys.version_info.serial), "windowsversion_major": str(windowsversion_major), "windowsversion_minor": str(windowsversion_minor), "windowsversion_build": str(windowsversion_build), "windowsversion_platform": str(windowsversion_platform), "windowsversion_service_pack": str(service_pack), "winver": str(sys.winver)} return results
def sys_func(): lists = sys.argv # 传递给Python脚本的命令行参数列表 => python p.py -> ['p.py'] / python p.py a 1 -> ['p.py', 'a', '1'] / 程序内执行 -> [''] strs = sys.getdefaultencoding() # 默认字符集名称 strs = sys.getfilesystemencoding() # 系统文件名字符集名称 num = sys.getrefcount(object) # 返回object的引用计数(比实际多1个) dicts = sys.modules # 已加载的模块, 可修改, 但不能通过修改返回的字典进行修改 lists = sys.path # 模块搜索路径 sys.path.append("./test") # 动态添加模块搜索路径 strs = sys.platform # 平台标识符(系统身份进行详细的检查,推荐使用) Linux:'linux' / Windows:'win32' / Cygwin:'cygwin' / Mac OS X:'darwin' strs = sys.version # python解释器版本 lists = sys.thread_info # 线程信息 num = sys.api_version # 解释器C API版本 types, value, back = sys.exc_info() # 捕获异常 详见 异常 文章的 excep() 代码块第二小部分(http://blog.csdn.net/rozol/article/details/69313164) sys.excepthook(types, value, back) # 打印异常 types = sys.last_type value = sys.last_value back = sys.last_traceback # sys.exit([arg]) // 引发SystemExit异常退出Python(可以try), 范围[0,127], None==0, "string"==1 sys.exit(0) num = sys.getrecursionlimit() # 最大递归数(堆栈最大深度), 详见 函数 文章(http://blog.csdn.net/rozol/article/details/69242050) sys.setrecursionlimit(5000) # 修改最大递归数 fnum = sys.getswitchinterval() # 获取线程切换间隔 sys.setswitchinterval(0.005) # 设置线程切换间隔, 单位秒 num = sys.getcheckinterval() # 解释器的检查间隔 sys.setcheckinterval(100) # 设置解释器检查间隔, 执行(默认)100个虚拟指令执行一次检查, 值为<=0时,检查每个虚拟指令 # sys.stdin // 标准输入流 strs = sys.stdin.readline()[:-1] # sys.stdout // 标准出入输出 sys.stdout.write(">>") sys.stdout.flush() # sys.stderr // 标注错误流 sys.stderr.write(">>") # --- lists = sys.builtin_module_names # 所有模块 (注:非导入模块) path = sys.base_exec_prefix # Python安装路径 path = sys.base_prefix # 同base_exec_prefix path = sys.exec_prefix # 同base_exec_prefix path = sys.prefix # 同base_exec_prefix path = sys.executable # Python解释器的绝对路径 strs = ys.byteorder # 本机字节顺序指示器, big-endian(最高有效字节在第一位)值为'big', little-endian(最低有效字节在第一位)值为'little' strs = sys.copyright # python版权 num = sys.hexversion # 16进制版本号 lists = sys.implementation # 当前运行的解释器的信息 num = sys.getallocatedblocks() # 解释器当前分配的内存块的数量 boolean = sys.dont_write_bytecode # 是否不会尝试导入源模块是写入.pyc文件 (False会写入.pyc文件) # sys.getsizeof(object[, default]) // 返回对象的大小bit, 只计算自身内存消耗,不计算引用对象的内存消耗, 调用对象的__sizeof__(), default没有获取到默认返回值 num = sys.getsizeof(object) boolean = sys.is_finalizing() # 解释器是否正在被关机 num = sys.maxsize # 最大整数值(2 ** 31 -1), 与系统有关 num = sys.maxunicode # 最大Unicode值的整数 (1114111) strs = sys.ps1 # 解释器主提示符 strs = sys.ps2 # 解释器次提示符 sys.call_tracing(func, ("arg",)) # 调用函数 sys._clear_type_cache() # 清除内部类型缓存 sys._debugmallocstats() # 打印CPython内存分配器状态的低级信息 sys.setprofile(profilefunc) # 设置profile函数, 默认None sys.getprofile() # 获取profile函数 sys.settrace(tracefunc) # 设置跟踪函数, def tracefunc(frame、event 和arg): sys.gettrace() # 获取跟踪函数, 默认None sys.set_coroutine_wrapper(wrapper) # 设置包装 def wrapper(coro): sys.get_coroutine_wrapper() # 包装, 默认None
def add_pymalloc_metrics(snapshot): # FIXME: test python version snapshot.add_metric('pymalloc.blocks', sys.getallocatedblocks(), 'int')
def track_memory_blocks(): while True: log_message('memory blocks', sys.getallocatedblocks()) time.sleep(1. / 30) # Check ~30 times per second
import sys import subprocess print('sys.argv ', sys.argv) print('sys.base_exec_prefix ', sys.base_exec_prefix) print('sys.base_prefix ', sys.base_prefix) print('sys.builtin_module_names ', sys.builtin_module_names) print('sys.byteorder ', sys.byteorder) print('sys.copyright ', sys.copyright) print('executing: ', sys.argv[0]) for i in range(len(sys.argv)): if i > 0: print(sys.argv[i]) subprocess.run(sys.argv[i]) print(sys._current_frames()) print(sys.exc_info()) print(sys.executable) print('get allocated blocks ', sys.getallocatedblocks()) print('get allocated blocks ', sys.getallocatedblocks()) print(sys.getswitchinterval()) sys.setswitchinterval(1000) print(sys.getswitchinterval()) sys._clear_type_cache() print('get allocated blocks after clear cache', sys.getallocatedblocks()) print(sys.version_info) #sys.call_tracing(sys.argv[0],sys.argv[1])
#using arrays,create a linear method of time complexity problem import array as a import time import matplotlib.pyplot as graph import sys print('enter loop value:',end='') input_value=input() #initilise/create an array temp=a.array('i',[2,3,4,6,7,8,9]) array_size=sys.getsizeof(temp) block_size=sys.getallocatedblocks() total_time_array=[] arr_len=[] print('initial allocated list size:',sys.getsizeof(arr_len)) print('array size and block size beforre the execution:',array_size,block_size) start_time=time.time() #capture starting execution time #increasing array length every time by 4 times for run_loop in range(0,int(input_value),1): arr_len.append(len(temp)) for k in range(0,10000): t=0 for j in range(1,5): temp.append(run_loop+j) end_time=time.time() #capture starting execution time total_time=round((end_time-start_time),7) total_time_array.append(total_time)