idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
20,800
def can_import ( api ) : if not has_binding ( api ) : return False current = loaded_api ( ) if api == QT_API_PYQT_DEFAULT : return current in [ QT_API_PYQT , QT_API_PYQTv1 , QT_API_PYQT5 , None ] else : return current in [ api , None ]
Safely query whether an API is importable without importing it
20,801
def extended_blank_lines ( logical_line , blank_lines , blank_before , indent_level , previous_logical ) : if previous_logical . startswith ( 'def ' ) : if blank_lines and pycodestyle . DOCSTRING_REGEX . match ( logical_line ) : yield ( 0 , 'E303 too many blank lines ({0})' . format ( blank_lines ) ) elif pycodestyle . DOCSTRING_REGEX . match ( previous_logical ) : if ( indent_level and not blank_lines and not blank_before and logical_line . startswith ( ( 'def ' ) ) and '(self' in logical_line ) : yield ( 0 , 'E301 expected 1 blank line, found 0' )
Check for missing blank lines after class declaration .
20,802
def fix_e265 ( source , aggressive = False ) : if '#' not in source : return source ignored_line_numbers = multiline_string_lines ( source , include_docstrings = True ) | set ( commented_out_code_lines ( source ) ) fixed_lines = [ ] sio = io . StringIO ( source ) for ( line_number , line ) in enumerate ( sio . readlines ( ) , start = 1 ) : if ( line . lstrip ( ) . startswith ( '#' ) and line_number not in ignored_line_numbers and not pycodestyle . noqa ( line ) ) : indentation = _get_indentation ( line ) line = line . lstrip ( ) if len ( line ) > 1 : pos = next ( ( index for index , c in enumerate ( line ) if c != '#' ) ) if ( ( line [ : pos ] . count ( '#' ) > 1 or line [ 1 ] . isalnum ( ) ) and not line . rstrip ( ) . endswith ( '#' ) ) : line = '# ' + line . lstrip ( '# \t' ) fixed_lines . append ( indentation + line ) else : fixed_lines . append ( line ) return '' . join ( fixed_lines )
Format block comments .
20,803
def refactor ( source , fixer_names , ignore = None , filename = '' ) : check_lib2to3 ( ) from lib2to3 import pgen2 try : new_text = refactor_with_2to3 ( source , fixer_names = fixer_names , filename = filename ) except ( pgen2 . parse . ParseError , SyntaxError , UnicodeDecodeError , UnicodeEncodeError ) : return source if ignore : if ignore in new_text and ignore not in source : return source return new_text
Return refactored code using lib2to3 .
20,804
def _get_indentation ( line ) : if line . strip ( ) : non_whitespace_index = len ( line ) - len ( line . lstrip ( ) ) return line [ : non_whitespace_index ] else : return ''
Return leading whitespace .
20,805
def _priority_key ( pep8_result ) : priority = [ 'e701' , 'e702' , 'e225' , 'e231' , 'e201' , 'e262' ] middle_index = 10000 lowest_priority = [ 'e501' ] key = pep8_result [ 'id' ] . lower ( ) try : return priority . index ( key ) except ValueError : try : return middle_index + lowest_priority . index ( key ) + 1 except ValueError : return middle_index
Key for sorting PEP8 results .
20,806
def normalize_multiline ( line ) : if line . startswith ( 'def ' ) and line . rstrip ( ) . endswith ( ':' ) : return line + ' pass' elif line . startswith ( 'return ' ) : return 'def _(): ' + line elif line . startswith ( '@' ) : return line + 'def _(): pass' elif line . startswith ( 'class ' ) : return line + ' pass' elif line . startswith ( ( 'if ' , 'elif ' , 'for ' , 'while ' ) ) : return line + ' pass' else : return line
Normalize multiline - related code that will cause syntax error .
20,807
def fix_whitespace ( line , offset , replacement ) : left = line [ : offset ] . rstrip ( '\n\r \t\\' ) right = line [ offset : ] . lstrip ( '\n\r \t\\' ) if right . startswith ( '#' ) : return line else : return left + replacement + right
Replace whitespace at offset and return fixed line .
20,808
def apply_global_fixes ( source , options , where = 'global' , filename = '' ) : if any ( code_match ( code , select = options . select , ignore = options . ignore ) for code in [ 'E101' , 'E111' ] ) : source = reindent ( source , indent_size = options . indent_size ) for ( code , function ) in global_fixes ( ) : if code_match ( code , select = options . select , ignore = options . ignore ) : if options . verbose : print ( '- . format ( where , code . upper ( ) ) , file = sys . stderr ) source = function ( source , aggressive = options . aggressive ) source = fix_2to3 ( source , aggressive = options . aggressive , select = options . select , ignore = options . ignore , filename = filename ) return source
Run global fixes on source code .
20,809
def main ( argv = None , apply_config = True ) : if argv is None : argv = sys . argv try : signal . signal ( signal . SIGPIPE , signal . SIG_DFL ) except AttributeError : pass try : args = parse_args ( argv [ 1 : ] , apply_config = apply_config ) if args . list_fixes : for code , description in sorted ( supported_fixes ( ) ) : print ( '{code} - {description}' . format ( code = code , description = description ) ) return 0 if args . files == [ '-' ] : assert not args . in_place encoding = sys . stdin . encoding or get_encoding ( ) wrap_output ( sys . stdout , encoding = encoding ) . write ( fix_code ( sys . stdin . read ( ) , args , encoding = encoding ) ) else : if args . in_place or args . diff : args . files = list ( set ( args . files ) ) else : assert len ( args . files ) == 1 assert not args . recursive fix_multiple_files ( args . files , args , sys . stdout ) except KeyboardInterrupt : return 1
Command - line entry .
20,810
def fix_e722 ( self , result ) : ( line_index , _ , target ) = get_index_offset_contents ( result , self . source ) if BARE_EXCEPT_REGEX . search ( target ) : self . source [ line_index ] = '{0}{1}' . format ( target [ : result [ 'column' ] - 1 ] , "except Exception:" )
fix bare except
20,811
def _split_after_delimiter ( self , item , indent_amt ) : self . _delete_whitespace ( ) if self . fits_on_current_line ( item . size ) : return last_space = None for item in reversed ( self . _lines ) : if ( last_space and ( not isinstance ( item , Atom ) or not item . is_colon ) ) : break else : last_space = None if isinstance ( item , self . _Space ) : last_space = item if isinstance ( item , ( self . _LineBreak , self . _Indent ) ) : return if not last_space : return self . add_line_break_at ( self . _lines . index ( last_space ) , indent_amt )
Split the line only after a delimiter .
20,812
def interact ( banner = None , readfunc = None , local = None ) : console = InteractiveConsole ( local ) if readfunc is not None : console . raw_input = readfunc else : try : import readline except ImportError : pass console . interact ( banner )
Closely emulate the interactive Python interpreter .
20,813
def runsource ( self , source , filename = "<input>" , symbol = "single" ) : try : code = self . compile ( source , filename , symbol ) except ( OverflowError , SyntaxError , ValueError ) : self . showsyntaxerror ( filename ) return False if code is None : return True self . runcode ( code ) return False
Compile and run some source in the interpreter .
20,814
def push ( self , line ) : self . buffer . append ( line ) source = "\n" . join ( self . buffer ) more = self . runsource ( source , self . filename ) if not more : self . resetbuffer ( ) return more
Push a line to the interpreter .
20,815
def show_in_pager ( self , strng , * args , ** kwargs ) : if isinstance ( strng , dict ) : strng = strng . get ( 'text/plain' , strng ) print ( strng )
Run a string through pager
20,816
def matchers ( self ) : return [ self . file_matches , self . magic_matches , self . python_func_kw_matches , self . dict_key_matches , ]
All active matcher routines for completion
20,817
def init_completer ( self ) : if IPythonRelease . _version_major >= 6 : self . Completer = self . _new_completer_600 ( ) elif IPythonRelease . _version_major >= 5 : self . Completer = self . _new_completer_500 ( ) elif IPythonRelease . _version_major >= 2 : self . Completer = self . _new_completer_234 ( ) elif IPythonRelease . _version_major >= 1 : self . Completer = self . _new_completer_100 ( ) if hasattr ( self . Completer , 'use_jedi' ) : self . Completer . use_jedi = False self . add_completer_hooks ( ) if IPythonRelease . _version_major <= 3 : if self . has_readline : self . set_readline_completer ( )
Initialize the completion machinery .
20,818
def open_handle ( self , dwDesiredAccess = win32 . PROCESS_ALL_ACCESS ) : hProcess = win32 . OpenProcess ( dwDesiredAccess , win32 . FALSE , self . dwProcessId ) try : self . close_handle ( ) except Exception : warnings . warn ( "Failed to close process handle: %s" % traceback . format_exc ( ) ) self . hProcess = hProcess
Opens a new handle to the process .
20,819
def close_handle ( self ) : try : if hasattr ( self . hProcess , 'close' ) : self . hProcess . close ( ) elif self . hProcess not in ( None , win32 . INVALID_HANDLE_VALUE ) : win32 . CloseHandle ( self . hProcess ) finally : self . hProcess = None
Closes the handle to the process .
20,820
def kill ( self , dwExitCode = 0 ) : hProcess = self . get_handle ( win32 . PROCESS_TERMINATE ) win32 . TerminateProcess ( hProcess , dwExitCode )
Terminates the execution of the process .
20,821
def suspend ( self ) : self . scan_threads ( ) suspended = list ( ) try : for aThread in self . iter_threads ( ) : aThread . suspend ( ) suspended . append ( aThread ) except Exception : for aThread in suspended : try : aThread . resume ( ) except Exception : pass raise
Suspends execution on all threads of the process .
20,822
def resume ( self ) : if self . get_thread_count ( ) == 0 : self . scan_threads ( ) resumed = list ( ) try : for aThread in self . iter_threads ( ) : aThread . resume ( ) resumed . append ( aThread ) except Exception : for aThread in resumed : try : aThread . suspend ( ) except Exception : pass raise
Resumes execution on all threads of the process .
20,823
def is_debugged ( self ) : hProcess = self . get_handle ( win32 . PROCESS_QUERY_INFORMATION ) return win32 . CheckRemoteDebuggerPresent ( hProcess )
Tries to determine if the process is being debugged by another process . It may detect other debuggers besides WinAppDbg .
20,824
def __fixup_labels ( self , disasm ) : for index in compat . xrange ( len ( disasm ) ) : ( address , size , text , dump ) = disasm [ index ] m = self . __hexa_parameter . search ( text ) while m : s , e = m . span ( ) value = text [ s : e ] try : label = self . get_label_at_address ( int ( value , 0x10 ) ) except Exception : label = None if label : text = text [ : s ] + label + text [ e : ] e = s + len ( value ) m = self . __hexa_parameter . search ( text , e ) disasm [ index ] = ( address , size , text , dump )
Private method used when disassembling from process memory .
20,825
def disassemble_current ( self , dwThreadId ) : aThread = self . get_thread ( dwThreadId ) return self . disassemble_instruction ( aThread . get_pc ( ) )
Disassemble the instruction at the program counter of the given thread .
20,826
def is_wow64 ( self ) : try : wow64 = self . __wow64 except AttributeError : if ( win32 . bits == 32 and not win32 . wow64 ) : wow64 = False else : if win32 . PROCESS_ALL_ACCESS == win32 . PROCESS_ALL_ACCESS_VISTA : dwAccess = win32 . PROCESS_QUERY_LIMITED_INFORMATION else : dwAccess = win32 . PROCESS_QUERY_INFORMATION hProcess = self . get_handle ( dwAccess ) try : wow64 = win32 . IsWow64Process ( hProcess ) except AttributeError : wow64 = False self . __wow64 = wow64 return wow64
Determines if the process is running under WOW64 .
20,827
def get_start_time ( self ) : if win32 . PROCESS_ALL_ACCESS == win32 . PROCESS_ALL_ACCESS_VISTA : dwAccess = win32 . PROCESS_QUERY_LIMITED_INFORMATION else : dwAccess = win32 . PROCESS_QUERY_INFORMATION hProcess = self . get_handle ( dwAccess ) CreationTime = win32 . GetProcessTimes ( hProcess ) [ 0 ] return win32 . FileTimeToSystemTime ( CreationTime )
Determines when has this process started running .
20,828
def get_exit_time ( self ) : if self . is_alive ( ) : ExitTime = win32 . GetSystemTimeAsFileTime ( ) else : if win32 . PROCESS_ALL_ACCESS == win32 . PROCESS_ALL_ACCESS_VISTA : dwAccess = win32 . PROCESS_QUERY_LIMITED_INFORMATION else : dwAccess = win32 . PROCESS_QUERY_INFORMATION hProcess = self . get_handle ( dwAccess ) ExitTime = win32 . GetProcessTimes ( hProcess ) [ 1 ] return win32 . FileTimeToSystemTime ( ExitTime )
Determines when has this process finished running . If the process is still alive the current time is returned instead .
20,829
def get_running_time ( self ) : if win32 . PROCESS_ALL_ACCESS == win32 . PROCESS_ALL_ACCESS_VISTA : dwAccess = win32 . PROCESS_QUERY_LIMITED_INFORMATION else : dwAccess = win32 . PROCESS_QUERY_INFORMATION hProcess = self . get_handle ( dwAccess ) ( CreationTime , ExitTime , _ , _ ) = win32 . GetProcessTimes ( hProcess ) if self . is_alive ( ) : ExitTime = win32 . GetSystemTimeAsFileTime ( ) CreationTime = CreationTime . dwLowDateTime + ( CreationTime . dwHighDateTime << 32 ) ExitTime = ExitTime . dwLowDateTime + ( ExitTime . dwHighDateTime << 32 ) RunningTime = ExitTime - CreationTime return RunningTime / 10000
Determines how long has this process been running .
20,830
def get_services ( self ) : self . __load_System_class ( ) pid = self . get_pid ( ) return [ d for d in System . get_active_services ( ) if d . ProcessId == pid ]
Retrieves the list of system services that are currently running in this process .
20,831
def get_peb_address ( self ) : try : return self . _peb_ptr except AttributeError : hProcess = self . get_handle ( win32 . PROCESS_QUERY_INFORMATION ) pbi = win32 . NtQueryInformationProcess ( hProcess , win32 . ProcessBasicInformation ) address = pbi . PebBaseAddress self . _peb_ptr = address return address
Returns a remote pointer to the PEB .
20,832
def get_command_line_block ( self ) : peb = self . get_peb ( ) pp = self . read_structure ( peb . ProcessParameters , win32 . RTL_USER_PROCESS_PARAMETERS ) s = pp . CommandLine return ( s . Buffer , s . MaximumLength )
Retrieves the command line block memory address and size .
20,833
def get_environment_block ( self ) : peb = self . get_peb ( ) pp = self . read_structure ( peb . ProcessParameters , win32 . RTL_USER_PROCESS_PARAMETERS ) Environment = pp . Environment try : EnvironmentSize = pp . EnvironmentSize except AttributeError : mbi = self . mquery ( Environment ) EnvironmentSize = mbi . RegionSize + mbi . BaseAddress - Environment return ( Environment , EnvironmentSize )
Retrieves the environment block memory address for the process .
20,834
def get_command_line ( self ) : ( Buffer , MaximumLength ) = self . get_command_line_block ( ) CommandLine = self . peek_string ( Buffer , dwMaxSize = MaximumLength , fUnicode = True ) gst = win32 . GuessStringType if gst . t_default == gst . t_ansi : CommandLine = CommandLine . encode ( 'cp1252' ) return CommandLine
Retrieves the command line with wich the program was started .
20,835
def get_environment_variables ( self ) : data = self . peek ( * self . get_environment_block ( ) ) tmp = ctypes . create_string_buffer ( data ) buffer = ctypes . create_unicode_buffer ( len ( data ) ) ctypes . memmove ( buffer , tmp , len ( data ) ) del tmp pos = 0 while buffer [ pos ] != u'\0' : pos += 1 pos += 1 environment = [ ] while buffer [ pos ] != u'\0' : env_name_pos = pos env_name = u'' found_name = False while buffer [ pos ] != u'\0' : char = buffer [ pos ] if char == u'=' : if env_name_pos == pos : env_name_pos += 1 pos += 1 continue pos += 1 found_name = True break env_name += char pos += 1 if not found_name : break env_value = u'' while buffer [ pos ] != u'\0' : env_value += buffer [ pos ] pos += 1 pos += 1 environment . append ( ( env_name , env_value ) ) if environment : environment . pop ( ) return environment
Retrieves the environment variables with wich the program is running .
20,836
def get_environment_data ( self , fUnicode = None ) : warnings . warn ( "Process.get_environment_data() is deprecated" " since WinAppDbg 1.5." , DeprecationWarning ) block = [ key + u'=' + value for ( key , value ) in self . get_environment_variables ( ) ] if fUnicode is None : gst = win32 . GuessStringType fUnicode = gst . t_default == gst . t_unicode if not fUnicode : block = [ x . encode ( 'cp1252' ) for x in block ] return block
Retrieves the environment block data with wich the program is running .
20,837
def parse_environment_data ( block ) : warnings . warn ( "Process.parse_environment_data() is deprecated" " since WinAppDbg 1.5." , DeprecationWarning ) environment = dict ( ) if not block : return environment gst = win32 . GuessStringType if type ( block [ 0 ] ) == gst . t_ansi : equals = '=' terminator = '\0' else : equals = u'=' terminator = u'\0' for chunk in block : sep = chunk . find ( equals , 1 ) if sep < 0 : continue key , value = chunk [ : sep ] , chunk [ sep + 1 : ] if key not in environment : environment [ key ] = value else : environment [ key ] += terminator + value return environment
Parse the environment block into a Python dictionary .
20,838
def get_environment ( self , fUnicode = None ) : variables = self . get_environment_variables ( ) if fUnicode is None : gst = win32 . GuessStringType fUnicode = gst . t_default == gst . t_unicode if not fUnicode : variables = [ ( key . encode ( 'cp1252' ) , value . encode ( 'cp1252' ) ) for ( key , value ) in variables ] environment = dict ( ) for key , value in variables : if key in environment : environment [ key ] = environment [ key ] + u'\0' + value else : environment [ key ] = value return environment
Retrieves the environment with wich the program is running .
20,839
def search_bytes ( self , bytes , minAddr = None , maxAddr = None ) : pattern = BytePattern ( bytes ) matches = Search . search_process ( self , pattern , minAddr , maxAddr ) for addr , size , data in matches : yield addr
Search for the given byte pattern within the process memory .
20,840
def search_text ( self , text , encoding = "utf-16le" , caseSensitive = False , minAddr = None , maxAddr = None ) : pattern = TextPattern ( text , encoding , caseSensitive ) matches = Search . search_process ( self , pattern , minAddr , maxAddr ) for addr , size , data in matches : yield addr , data
Search for the given text within the process memory .
20,841
def search_regexp ( self , regexp , flags = 0 , minAddr = None , maxAddr = None , bufferPages = - 1 ) : pattern = RegExpPattern ( regexp , flags ) return Search . search_process ( self , pattern , minAddr , maxAddr , bufferPages )
Search for the given regular expression within the process memory .
20,842
def search_hexa ( self , hexa , minAddr = None , maxAddr = None ) : pattern = HexPattern ( hexa ) matches = Search . search_process ( self , pattern , minAddr , maxAddr ) for addr , size , data in matches : yield addr , data
Search for the given hexadecimal pattern within the process memory .
20,843
def read ( self , lpBaseAddress , nSize ) : hProcess = self . get_handle ( win32 . PROCESS_VM_READ | win32 . PROCESS_QUERY_INFORMATION ) if not self . is_buffer ( lpBaseAddress , nSize ) : raise ctypes . WinError ( win32 . ERROR_INVALID_ADDRESS ) data = win32 . ReadProcessMemory ( hProcess , lpBaseAddress , nSize ) if len ( data ) != nSize : raise ctypes . WinError ( ) return data
Reads from the memory of the process .
20,844
def read_int ( self , lpBaseAddress ) : return self . __read_c_type ( lpBaseAddress , compat . b ( '@l' ) , ctypes . c_int )
Reads a signed integer from the memory of the process .
20,845
def read_structure ( self , lpBaseAddress , stype ) : if type ( lpBaseAddress ) not in ( type ( 0 ) , type ( long ( 0 ) ) ) : lpBaseAddress = ctypes . cast ( lpBaseAddress , ctypes . c_void_p ) data = self . read ( lpBaseAddress , ctypes . sizeof ( stype ) ) buff = ctypes . create_string_buffer ( data ) ptr = ctypes . cast ( ctypes . pointer ( buff ) , ctypes . POINTER ( stype ) ) return ptr . contents
Reads a ctypes structure from the memory of the process .
20,846
def read_string ( self , lpBaseAddress , nChars , fUnicode = False ) : if fUnicode : nChars = nChars * 2 szString = self . read ( lpBaseAddress , nChars ) if fUnicode : szString = compat . unicode ( szString , 'U16' , 'ignore' ) return szString
Reads an ASCII or Unicode string from the address space of the process .
20,847
def peek ( self , lpBaseAddress , nSize ) : data = '' if nSize > 0 : try : hProcess = self . get_handle ( win32 . PROCESS_VM_READ | win32 . PROCESS_QUERY_INFORMATION ) for mbi in self . get_memory_map ( lpBaseAddress , lpBaseAddress + nSize ) : if not mbi . is_readable ( ) : nSize = mbi . BaseAddress - lpBaseAddress break if nSize > 0 : data = win32 . ReadProcessMemory ( hProcess , lpBaseAddress , nSize ) except WindowsError : e = sys . exc_info ( ) [ 1 ] msg = "Error reading process %d address %s: %s" msg %= ( self . get_pid ( ) , HexDump . address ( lpBaseAddress ) , e . strerror ) warnings . warn ( msg ) return data
Reads the memory of the process .
20,848
def peek_char ( self , lpBaseAddress ) : char = self . peek ( lpBaseAddress , 1 ) if char : return ord ( char ) return 0
Reads a single character from the memory of the process .
20,849
def peek_string ( self , lpBaseAddress , fUnicode = False , dwMaxSize = 0x1000 ) : if not lpBaseAddress or dwMaxSize == 0 : if fUnicode : return u'' return '' if not dwMaxSize : dwMaxSize = 0x1000 szString = self . peek ( lpBaseAddress , dwMaxSize ) if fUnicode : szString = compat . unicode ( szString , 'U16' , 'replace' ) szString = szString [ : szString . find ( u'\0' ) ] else : szString = szString [ : szString . find ( '\0' ) ] return szString
Tries to read an ASCII or Unicode string from the address space of the process .
20,850
def malloc ( self , dwSize , lpAddress = None ) : hProcess = self . get_handle ( win32 . PROCESS_VM_OPERATION ) return win32 . VirtualAllocEx ( hProcess , lpAddress , dwSize )
Allocates memory into the address space of the process .
20,851
def mprotect ( self , lpAddress , dwSize , flNewProtect ) : hProcess = self . get_handle ( win32 . PROCESS_VM_OPERATION ) return win32 . VirtualProtectEx ( hProcess , lpAddress , dwSize , flNewProtect )
Set memory protection in the address space of the process .
20,852
def free ( self , lpAddress ) : hProcess = self . get_handle ( win32 . PROCESS_VM_OPERATION ) win32 . VirtualFreeEx ( hProcess , lpAddress )
Frees memory from the address space of the process .
20,853
def is_pointer ( self , address ) : try : mbi = self . mquery ( address ) except WindowsError : e = sys . exc_info ( ) [ 1 ] if e . winerror == win32 . ERROR_INVALID_PARAMETER : return False raise return mbi . has_content ( )
Determines if an address is a valid code or data pointer .
20,854
def is_address_valid ( self , address ) : try : mbi = self . mquery ( address ) except WindowsError : e = sys . exc_info ( ) [ 1 ] if e . winerror == win32 . ERROR_INVALID_PARAMETER : return False raise return True
Determines if an address is a valid user mode address .
20,855
def is_address_free ( self , address ) : try : mbi = self . mquery ( address ) except WindowsError : e = sys . exc_info ( ) [ 1 ] if e . winerror == win32 . ERROR_INVALID_PARAMETER : return False raise return mbi . is_free ( )
Determines if an address belongs to a free page .
20,856
def is_address_reserved ( self , address ) : try : mbi = self . mquery ( address ) except WindowsError : e = sys . exc_info ( ) [ 1 ] if e . winerror == win32 . ERROR_INVALID_PARAMETER : return False raise return mbi . is_reserved ( )
Determines if an address belongs to a reserved page .
20,857
def is_address_commited ( self , address ) : try : mbi = self . mquery ( address ) except WindowsError : e = sys . exc_info ( ) [ 1 ] if e . winerror == win32 . ERROR_INVALID_PARAMETER : return False raise return mbi . is_commited ( )
Determines if an address belongs to a commited page .
20,858
def is_address_guard ( self , address ) : try : mbi = self . mquery ( address ) except WindowsError : e = sys . exc_info ( ) [ 1 ] if e . winerror == win32 . ERROR_INVALID_PARAMETER : return False raise return mbi . is_guard ( )
Determines if an address belongs to a guard page .
20,859
def is_address_readable ( self , address ) : try : mbi = self . mquery ( address ) except WindowsError : e = sys . exc_info ( ) [ 1 ] if e . winerror == win32 . ERROR_INVALID_PARAMETER : return False raise return mbi . is_readable ( )
Determines if an address belongs to a commited and readable page . The page may or may not have additional permissions .
20,860
def is_address_writeable ( self , address ) : try : mbi = self . mquery ( address ) except WindowsError : e = sys . exc_info ( ) [ 1 ] if e . winerror == win32 . ERROR_INVALID_PARAMETER : return False raise return mbi . is_writeable ( )
Determines if an address belongs to a commited and writeable page . The page may or may not have additional permissions .
20,861
def is_address_copy_on_write ( self , address ) : try : mbi = self . mquery ( address ) except WindowsError : e = sys . exc_info ( ) [ 1 ] if e . winerror == win32 . ERROR_INVALID_PARAMETER : return False raise return mbi . is_copy_on_write ( )
Determines if an address belongs to a commited copy - on - write page . The page may or may not have additional permissions .
20,862
def is_address_executable ( self , address ) : try : mbi = self . mquery ( address ) except WindowsError : e = sys . exc_info ( ) [ 1 ] if e . winerror == win32 . ERROR_INVALID_PARAMETER : return False raise return mbi . is_executable ( )
Determines if an address belongs to a commited and executable page . The page may or may not have additional permissions .
20,863
def is_address_executable_and_writeable ( self , address ) : try : mbi = self . mquery ( address ) except WindowsError : e = sys . exc_info ( ) [ 1 ] if e . winerror == win32 . ERROR_INVALID_PARAMETER : return False raise return mbi . is_executable_and_writeable ( )
Determines if an address belongs to a commited writeable and executable page . The page may or may not have additional permissions .
20,864
def is_buffer ( self , address , size ) : if size <= 0 : raise ValueError ( "The size argument must be greater than zero" ) while size > 0 : try : mbi = self . mquery ( address ) except WindowsError : e = sys . exc_info ( ) [ 1 ] if e . winerror == win32 . ERROR_INVALID_PARAMETER : return False raise if not mbi . has_content ( ) : return False size = size - mbi . RegionSize return True
Determines if the given memory area is a valid code or data buffer .
20,865
def iter_memory_map ( self , minAddr = None , maxAddr = None ) : minAddr , maxAddr = MemoryAddresses . align_address_range ( minAddr , maxAddr ) prevAddr = minAddr - 1 currentAddr = minAddr while prevAddr < currentAddr < maxAddr : try : mbi = self . mquery ( currentAddr ) except WindowsError : e = sys . exc_info ( ) [ 1 ] if e . winerror == win32 . ERROR_INVALID_PARAMETER : break raise yield mbi prevAddr = currentAddr currentAddr = mbi . BaseAddress + mbi . RegionSize
Produces an iterator over the memory map to the process address space .
20,866
def get_mapped_filenames ( self , memoryMap = None ) : hProcess = self . get_handle ( win32 . PROCESS_VM_READ | win32 . PROCESS_QUERY_INFORMATION ) if not memoryMap : memoryMap = self . get_memory_map ( ) mappedFilenames = dict ( ) for mbi in memoryMap : if mbi . Type not in ( win32 . MEM_IMAGE , win32 . MEM_MAPPED ) : continue baseAddress = mbi . BaseAddress fileName = "" try : fileName = win32 . GetMappedFileName ( hProcess , baseAddress ) fileName = PathOperations . native_to_win32_pathname ( fileName ) except WindowsError : pass mappedFilenames [ baseAddress ] = fileName return mappedFilenames
Retrieves the filenames for memory mapped files in the debugee .
20,867
def iter_memory_snapshot ( self , minAddr = None , maxAddr = None ) : memory = self . get_memory_map ( minAddr , maxAddr ) if not memory : return try : filenames = self . get_mapped_filenames ( memory ) except WindowsError : e = sys . exc_info ( ) [ 1 ] if e . winerror != win32 . ERROR_ACCESS_DENIED : raise filenames = dict ( ) if minAddr is not None : minAddr = MemoryAddresses . align_address_to_page_start ( minAddr ) mbi = memory [ 0 ] if mbi . BaseAddress < minAddr : mbi . RegionSize = mbi . BaseAddress + mbi . RegionSize - minAddr mbi . BaseAddress = minAddr if maxAddr is not None : if maxAddr != MemoryAddresses . align_address_to_page_start ( maxAddr ) : maxAddr = MemoryAddresses . align_address_to_page_end ( maxAddr ) mbi = memory [ - 1 ] if mbi . BaseAddress + mbi . RegionSize > maxAddr : mbi . RegionSize = maxAddr - mbi . BaseAddress while memory : mbi = memory . pop ( 0 ) mbi . filename = filenames . get ( mbi . BaseAddress , None ) if mbi . has_content ( ) : mbi . content = self . read ( mbi . BaseAddress , mbi . RegionSize ) else : mbi . content = None yield mbi
Returns an iterator that allows you to go through the memory contents of a process .
20,868
def restore_memory_snapshot ( self , snapshot , bSkipMappedFiles = True , bSkipOnError = False ) : if not snapshot or not isinstance ( snapshot , list ) or not isinstance ( snapshot [ 0 ] , win32 . MemoryBasicInformation ) : raise TypeError ( "Only snapshots returned by " "take_memory_snapshot() can be used here." ) hProcess = self . get_handle ( win32 . PROCESS_VM_WRITE | win32 . PROCESS_VM_OPERATION | win32 . PROCESS_SUSPEND_RESUME | win32 . PROCESS_QUERY_INFORMATION ) self . suspend ( ) try : for old_mbi in snapshot : new_mbi = self . mquery ( old_mbi . BaseAddress ) if new_mbi . BaseAddress == old_mbi . BaseAddress and new_mbi . RegionSize == old_mbi . RegionSize : self . __restore_mbi ( hProcess , new_mbi , old_mbi , bSkipMappedFiles ) else : old_mbi = win32 . MemoryBasicInformation ( old_mbi ) old_start = old_mbi . BaseAddress old_end = old_start + old_mbi . RegionSize new_start = new_mbi . BaseAddress new_end = new_start + new_mbi . RegionSize if old_start > new_start : start = old_start else : start = new_start if old_end < new_end : end = old_end else : end = new_end step = MemoryAddresses . pageSize old_mbi . RegionSize = step new_mbi . RegionSize = step address = start while address < end : old_mbi . BaseAddress = address new_mbi . BaseAddress = address self . __restore_mbi ( hProcess , new_mbi , old_mbi , bSkipMappedFiles , bSkipOnError ) address = address + step finally : self . resume ( )
Attempts to restore the memory state as it was when the given snapshot was taken .
20,869
def inject_code ( self , payload , lpParameter = 0 ) : lpStartAddress = self . malloc ( len ( payload ) ) try : self . write ( lpStartAddress , payload ) aThread = self . start_thread ( lpStartAddress , lpParameter , bSuspended = False ) aThread . pInjectedMemory = lpStartAddress except Exception : self . free ( lpStartAddress ) raise return aThread , lpStartAddress
Injects relocatable code into the process memory and executes it .
20,870
def get_pid_from_tid ( self , dwThreadId ) : try : try : hThread = win32 . OpenThread ( win32 . THREAD_QUERY_LIMITED_INFORMATION , False , dwThreadId ) except WindowsError : e = sys . exc_info ( ) [ 1 ] if e . winerror != win32 . ERROR_ACCESS_DENIED : raise hThread = win32 . OpenThread ( win32 . THREAD_QUERY_INFORMATION , False , dwThreadId ) try : return win32 . GetProcessIdOfThread ( hThread ) finally : hThread . close ( ) except Exception : for aProcess in self . iter_processes ( ) : if aProcess . has_thread ( dwThreadId ) : return aProcess . get_pid ( ) self . scan_processes_and_threads ( ) for aProcess in self . iter_processes ( ) : if aProcess . has_thread ( dwThreadId ) : return aProcess . get_pid ( ) msg = "Unknown thread ID %d" % dwThreadId raise KeyError ( msg )
Retrieves the global ID of the process that owns the thread .
20,871
def argv_to_cmdline ( argv ) : cmdline = list ( ) for token in argv : if not token : token = '""' else : if '"' in token : token = token . replace ( '"' , '\\"' ) if ' ' in token or '\t' in token or '\n' in token or '\r' in token : token = '"%s"' % token cmdline . append ( token ) return ' ' . join ( cmdline )
Convert a list of arguments to a single command line string .
20,872
def get_explorer_pid ( self ) : try : exp = win32 . SHGetFolderPath ( win32 . CSIDL_WINDOWS ) except Exception : exp = None if not exp : exp = os . getenv ( 'SystemRoot' ) if exp : exp = os . path . join ( exp , 'explorer.exe' ) exp_list = self . find_processes_by_filename ( exp ) if exp_list : return exp_list [ 0 ] [ 0 ] . get_pid ( ) return None
Tries to find the process ID for explorer . exe .
20,873
def scan ( self ) : has_threads = True try : try : self . scan_processes_and_threads ( ) except Exception : self . scan_processes_fast ( ) for aProcess in self . __processDict . values ( ) : if aProcess . _get_thread_ids ( ) : try : aProcess . scan_threads ( ) except WindowsError : has_threads = False finally : self . scan_processes ( ) has_modules = self . scan_modules ( ) has_full_names = self . scan_process_filenames ( ) return has_threads and has_modules and has_full_names
Populates the snapshot with running processes and threads and loaded modules .
20,874
def scan_processes_and_threads ( self ) : our_pid = win32 . GetCurrentProcessId ( ) dead_pids = set ( compat . iterkeys ( self . __processDict ) ) found_tids = set ( ) if our_pid in dead_pids : dead_pids . remove ( our_pid ) dwFlags = win32 . TH32CS_SNAPPROCESS | win32 . TH32CS_SNAPTHREAD with win32 . CreateToolhelp32Snapshot ( dwFlags ) as hSnapshot : pe = win32 . Process32First ( hSnapshot ) while pe is not None : dwProcessId = pe . th32ProcessID if dwProcessId != our_pid : if dwProcessId in dead_pids : dead_pids . remove ( dwProcessId ) if dwProcessId not in self . __processDict : aProcess = Process ( dwProcessId , fileName = pe . szExeFile ) self . _add_process ( aProcess ) elif pe . szExeFile : aProcess = self . get_process ( dwProcessId ) if not aProcess . fileName : aProcess . fileName = pe . szExeFile pe = win32 . Process32Next ( hSnapshot ) te = win32 . Thread32First ( hSnapshot ) while te is not None : dwProcessId = te . th32OwnerProcessID if dwProcessId != our_pid : if dwProcessId in dead_pids : dead_pids . remove ( dwProcessId ) if dwProcessId in self . __processDict : aProcess = self . get_process ( dwProcessId ) else : aProcess = Process ( dwProcessId ) self . _add_process ( aProcess ) dwThreadId = te . th32ThreadID found_tids . add ( dwThreadId ) if not aProcess . _has_thread_id ( dwThreadId ) : aThread = Thread ( dwThreadId , process = aProcess ) aProcess . _add_thread ( aThread ) te = win32 . Thread32Next ( hSnapshot ) for pid in dead_pids : self . _del_process ( pid ) for aProcess in compat . itervalues ( self . __processDict ) : dead_tids = set ( aProcess . _get_thread_ids ( ) ) dead_tids . difference_update ( found_tids ) for tid in dead_tids : aProcess . _del_thread ( tid )
Populates the snapshot with running processes and threads .
20,875
def scan_processes ( self ) : our_pid = win32 . GetCurrentProcessId ( ) dead_pids = set ( compat . iterkeys ( self . __processDict ) ) if our_pid in dead_pids : dead_pids . remove ( our_pid ) pProcessInfo = None try : pProcessInfo , dwCount = win32 . WTSEnumerateProcesses ( win32 . WTS_CURRENT_SERVER_HANDLE ) for index in compat . xrange ( dwCount ) : sProcessInfo = pProcessInfo [ index ] pid = sProcessInfo . ProcessId if pid == our_pid : continue if pid in dead_pids : dead_pids . remove ( pid ) fileName = sProcessInfo . pProcessName if pid not in self . __processDict : aProcess = Process ( pid , fileName = fileName ) self . _add_process ( aProcess ) elif fileName : aProcess = self . __processDict . get ( pid ) if not aProcess . fileName : aProcess . fileName = fileName finally : if pProcessInfo is not None : try : win32 . WTSFreeMemory ( pProcessInfo ) except WindowsError : pass for pid in dead_pids : self . _del_process ( pid )
Populates the snapshot with running processes .
20,876
def scan_processes_fast ( self ) : new_pids = set ( win32 . EnumProcesses ( ) ) old_pids = set ( compat . iterkeys ( self . __processDict ) ) our_pid = win32 . GetCurrentProcessId ( ) if our_pid in new_pids : new_pids . remove ( our_pid ) if our_pid in old_pids : old_pids . remove ( our_pid ) for pid in new_pids . difference ( old_pids ) : self . _add_process ( Process ( pid ) ) for pid in old_pids . difference ( new_pids ) : self . _del_process ( pid )
Populates the snapshot with running processes . Only the PID is retrieved for each process .
20,877
def scan_process_filenames ( self ) : complete = True for aProcess in self . __processDict . values ( ) : try : new_name = None old_name = aProcess . fileName try : aProcess . fileName = None new_name = aProcess . get_filename ( ) finally : if not new_name : aProcess . fileName = old_name complete = False except Exception : complete = False return complete
Update the filename for each process in the snapshot when possible .
20,878
def clear_dead_processes ( self ) : for pid in self . get_process_ids ( ) : aProcess = self . get_process ( pid ) if not aProcess . is_alive ( ) : self . _del_process ( aProcess )
Removes Process objects from the snapshot referring to processes no longer running .
20,879
def clear_unattached_processes ( self ) : for pid in self . get_process_ids ( ) : aProcess = self . get_process ( pid ) if not aProcess . is_being_debugged ( ) : self . _del_process ( aProcess )
Removes Process objects from the snapshot referring to processes not being debugged .
20,880
def close_process_handles ( self ) : for pid in self . get_process_ids ( ) : aProcess = self . get_process ( pid ) try : aProcess . close_handle ( ) except Exception : e = sys . exc_info ( ) [ 1 ] try : msg = "Cannot close process handle %s, reason: %s" msg %= ( aProcess . hProcess . value , str ( e ) ) warnings . warn ( msg ) except Exception : pass
Closes all open handles to processes in this snapshot .
20,881
def close_process_and_thread_handles ( self ) : for aProcess in self . iter_processes ( ) : aProcess . close_thread_handles ( ) try : aProcess . close_handle ( ) except Exception : e = sys . exc_info ( ) [ 1 ] try : msg = "Cannot close process handle %s, reason: %s" msg %= ( aProcess . hProcess . value , str ( e ) ) warnings . warn ( msg ) except Exception : pass
Closes all open handles to processes and threads in this snapshot .
20,882
def _add_process ( self , aProcess ) : dwProcessId = aProcess . dwProcessId self . __processDict [ dwProcessId ] = aProcess
Private method to add a process object to the snapshot .
20,883
def _del_process ( self , dwProcessId ) : try : aProcess = self . __processDict [ dwProcessId ] del self . __processDict [ dwProcessId ] except KeyError : aProcess = None msg = "Unknown process ID %d" % dwProcessId warnings . warn ( msg , RuntimeWarning ) if aProcess : aProcess . clear ( )
Private method to remove a process object from the snapshot .
20,884
def ismethoddescriptor ( object ) : return ( hasattr ( object , "__get__" ) and not hasattr ( object , "__set__" ) and not ismethod ( object ) and not isfunction ( object ) and not isclass ( object ) )
Return true if the object is a method descriptor .
20,885
def isroutine ( object ) : return ( isbuiltin ( object ) or isfunction ( object ) or ismethod ( object ) or ismethoddescriptor ( object ) )
Return true if the object is any kind of function or method .
20,886
def classify_class_attrs ( cls ) : mro = getmro ( cls ) names = dir ( cls ) result = [ ] for name in names : if name in cls . __dict__ : obj = cls . __dict__ [ name ] else : obj = getattr ( cls , name ) homecls = getattr ( obj , "__objclass__" , None ) if homecls is None : for base in mro : if name in base . __dict__ : homecls = base break if homecls is not None and name in homecls . __dict__ : obj = homecls . __dict__ [ name ] obj_via_getattr = getattr ( cls , name ) if isinstance ( obj , staticmethod ) : kind = "static method" elif isinstance ( obj , classmethod ) : kind = "class method" elif isinstance ( obj , property ) : kind = "property" elif ( ismethod ( obj_via_getattr ) or ismethoddescriptor ( obj_via_getattr ) ) : kind = "method" else : kind = "data" result . append ( ( name , kind , homecls , obj ) ) return result
Return list of attribute - descriptor tuples .
20,887
def indentsize ( line ) : expline = string . expandtabs ( line ) return len ( expline ) - len ( string . lstrip ( expline ) )
Return the indent size in spaces at the start of a line of text .
20,888
def getdoc ( object ) : try : doc = object . __doc__ except AttributeError : return None if not isinstance ( doc , ( str , unicode ) ) : return None try : lines = string . split ( string . expandtabs ( doc ) , '\n' ) except UnicodeError : return None else : margin = None for line in lines [ 1 : ] : content = len ( string . lstrip ( line ) ) if not content : continue indent = len ( line ) - content if margin is None : margin = indent else : margin = min ( margin , indent ) if margin is not None : for i in range ( 1 , len ( lines ) ) : lines [ i ] = lines [ i ] [ margin : ] return string . join ( lines , '\n' )
Get the documentation string for an object .
20,889
def getfile ( object ) : if ismodule ( object ) : if hasattr ( object , '__file__' ) : return object . __file__ raise TypeError , 'arg is a built-in module' if isclass ( object ) : object = sys . modules . get ( object . __module__ ) if hasattr ( object , '__file__' ) : return object . __file__ raise TypeError , 'arg is a built-in class' if ismethod ( object ) : object = object . im_func if isfunction ( object ) : object = object . func_code if istraceback ( object ) : object = object . tb_frame if isframe ( object ) : object = object . f_code if iscode ( object ) : return object . co_filename raise TypeError , 'arg is not a module, class, method, ' 'function, traceback, frame, or code object'
Work out which source or compiled file an object was defined in .
20,890
def getmoduleinfo ( path ) : filename = os . path . basename ( path ) suffixes = map ( lambda ( suffix , mode , mtype ) : ( - len ( suffix ) , suffix , mode , mtype ) , imp . get_suffixes ( ) ) suffixes . sort ( ) for neglen , suffix , mode , mtype in suffixes : if filename [ neglen : ] == suffix : return filename [ : neglen ] , suffix , mode , mtype
Get the module name suffix mode and module type for a given file .
20,891
def getsourcefile ( object ) : filename = getfile ( object ) if string . lower ( filename [ - 4 : ] ) in [ '.pyc' , '.pyo' ] : filename = filename [ : - 4 ] + '.py' for suffix , mode , kind in imp . get_suffixes ( ) : if 'b' in mode and string . lower ( filename [ - len ( suffix ) : ] ) == suffix : return None if os . path . exists ( filename ) : return filename
Return the Python source file an object was defined in if it exists .
20,892
def getabsfile ( object ) : return os . path . normcase ( os . path . abspath ( getsourcefile ( object ) or getfile ( object ) ) )
Return an absolute path to the source or compiled file for an object .
20,893
def getmodule ( object ) : if ismodule ( object ) : return object if isclass ( object ) : return sys . modules . get ( object . __module__ ) try : file = getabsfile ( object ) except TypeError : return None if modulesbyfile . has_key ( file ) : return sys . modules [ modulesbyfile [ file ] ] for module in sys . modules . values ( ) : if hasattr ( module , '__file__' ) : modulesbyfile [ getabsfile ( module ) ] = module . __name__ if modulesbyfile . has_key ( file ) : return sys . modules [ modulesbyfile [ file ] ] main = sys . modules [ '__main__' ] if hasattr ( main , object . __name__ ) : mainobject = getattr ( main , object . __name__ ) if mainobject is object : return main builtin = sys . modules [ '__builtin__' ] if hasattr ( builtin , object . __name__ ) : builtinobject = getattr ( builtin , object . __name__ ) if builtinobject is object : return builtin
Return the module an object was defined in or None if not found .
20,894
def findsource ( object ) : try : file = open ( getsourcefile ( object ) ) except ( TypeError , IOError ) : raise IOError , 'could not get source code' lines = file . readlines ( ) file . close ( ) if ismodule ( object ) : return lines , 0 if isclass ( object ) : name = object . __name__ pat = re . compile ( r'^\s*class\s*' + name + r'\b' ) for i in range ( len ( lines ) ) : if pat . match ( lines [ i ] ) : return lines , i else : raise IOError , 'could not find class definition' if ismethod ( object ) : object = object . im_func if isfunction ( object ) : object = object . func_code if istraceback ( object ) : object = object . tb_frame if isframe ( object ) : object = object . f_code if iscode ( object ) : if not hasattr ( object , 'co_firstlineno' ) : raise IOError , 'could not find function definition' lnum = object . co_firstlineno - 1 pat = re . compile ( r'^(\s*def\s)|(.*\slambda(:|\s))' ) while lnum > 0 : if pat . match ( lines [ lnum ] ) : break lnum = lnum - 1 return lines , lnum raise IOError , 'could not find code object'
Return the entire source file and starting line number for an object .
20,895
def getcomments ( object ) : try : lines , lnum = findsource ( object ) except IOError : return None if ismodule ( object ) : start = 0 if lines and lines [ 0 ] [ : 2 ] == '#!' : start = 1 while start < len ( lines ) and string . strip ( lines [ start ] ) in [ '' , '#' ] : start = start + 1 if start < len ( lines ) and lines [ start ] [ : 1 ] == '#' : comments = [ ] end = start while end < len ( lines ) and lines [ end ] [ : 1 ] == '#' : comments . append ( string . expandtabs ( lines [ end ] ) ) end = end + 1 return string . join ( comments , '' ) elif lnum > 0 : indent = indentsize ( lines [ lnum ] ) end = lnum - 1 if end >= 0 and string . lstrip ( lines [ end ] ) [ : 1 ] == '#' and indentsize ( lines [ end ] ) == indent : comments = [ string . lstrip ( string . expandtabs ( lines [ end ] ) ) ] if end > 0 : end = end - 1 comment = string . lstrip ( string . expandtabs ( lines [ end ] ) ) while comment [ : 1 ] == '#' and indentsize ( lines [ end ] ) == indent : comments [ : 0 ] = [ comment ] end = end - 1 if end < 0 : break comment = string . lstrip ( string . expandtabs ( lines [ end ] ) ) while comments and string . strip ( comments [ 0 ] ) == '#' : comments [ : 1 ] = [ ] while comments and string . strip ( comments [ - 1 ] ) == '#' : comments [ - 1 : ] = [ ] return string . join ( comments , '' )
Get lines of comments immediately preceding an object s source code .
20,896
def getblock ( lines ) : try : tokenize . tokenize ( ListReader ( lines ) . readline , BlockFinder ( ) . tokeneater ) except EndOfBlock , eob : return lines [ : eob . args [ 0 ] ] return lines [ : 1 ]
Extract the block of code at the top of the given list of lines .
20,897
def getsourcelines ( object ) : lines , lnum = findsource ( object ) if ismodule ( object ) : return lines , 0 else : return getblock ( lines [ lnum : ] ) , lnum + 1
Return a list of source lines and starting line number for an object .
20,898
def getclasstree ( classes , unique = 0 ) : children = { } roots = [ ] for c in classes : if c . __bases__ : for parent in c . __bases__ : if not children . has_key ( parent ) : children [ parent ] = [ ] children [ parent ] . append ( c ) if unique and parent in classes : break elif c not in roots : roots . append ( c ) for parent in children . keys ( ) : if parent not in classes : roots . append ( parent ) return walktree ( roots , children , None )
Arrange the given list of classes into a hierarchy of nested lists .
20,899
def getargs ( co ) : if not iscode ( co ) : raise TypeError , 'arg is not a code object' nargs = co . co_argcount names = co . co_varnames args = list ( names [ : nargs ] ) step = 0 if not sys . platform . startswith ( 'java' ) : code = co . co_code import dis for i in range ( nargs ) : if args [ i ] [ : 1 ] in [ '' , '.' ] : stack , remain , count = [ ] , [ ] , [ ] while step < len ( code ) : op = ord ( code [ step ] ) step = step + 1 if op >= dis . HAVE_ARGUMENT : opname = dis . opname [ op ] value = ord ( code [ step ] ) + ord ( code [ step + 1 ] ) * 256 step = step + 2 if opname in [ 'UNPACK_TUPLE' , 'UNPACK_SEQUENCE' ] : remain . append ( value ) count . append ( value ) elif opname == 'STORE_FAST' : stack . append ( names [ value ] ) remain [ - 1 ] = remain [ - 1 ] - 1 while remain [ - 1 ] == 0 : remain . pop ( ) size = count . pop ( ) stack [ - size : ] = [ stack [ - size : ] ] if not remain : break remain [ - 1 ] = remain [ - 1 ] - 1 if not remain : break args [ i ] = stack [ 0 ] varargs = None if co . co_flags & CO_VARARGS : varargs = co . co_varnames [ nargs ] nargs = nargs + 1 varkw = None if co . co_flags & CO_VARKEYWORDS : varkw = co . co_varnames [ nargs ] return args , varargs , varkw
Get information about the arguments accepted by a code object .