pyrevit.coreutils

Misc Helper functions for pyRevit.

Example

>>> from pyrevit import coreutils
>>> coreutils.cleanup_string('some string')
class pyrevit.coreutils.FileWatcher(filepath)

Bases: object

Simple file version watcher.

This is a simple utility class to look for changes in a file based on its timestamp.

Example

>>> watcher = FileWatcher('/path/to/file.ext')
>>> watcher.has_changed
True
has_changed

Compare current file timestamp to the cached timestamp.

update_tstamp()

Update the cached timestamp for later comparison.

class pyrevit.coreutils.SafeDict

Bases: dict

Dictionary that does not fail on any key.

This is a dictionary subclass to help with string formatting with unknown key values.

Example

>>> string = '{target} {attr} is {color}.'
>>> safedict = SafeDict({'target': 'Apple',
...                      'attr':   'Color'})
>>> string.format(safedict)  # will not fail with missing 'color' key
'Apple Color is {color}.'
class pyrevit.coreutils.ScriptFileParser(file_address)

Bases: object

Parse python script to extract variables and docstrings.

Primarily designed to assist pyRevit in determining script configurations but can work for any python script.

Example

>>> finder = ScriptFileParser('/path/to/coreutils/__init__.py')
>>> finder.docstring()
... "Misc Helper functions for pyRevit."
>>> finder.extract_param('SomeValue', [])
[]
extract_node_value(node)

Manual extraction of values from node

extract_param(param_name, default_value=None)

Find variable and extract its value.

Parameters:
  • param_name (str) – variable name
  • default_value (any) – default value to be returned if variable does not exist
Returns:

value of the variable or None

Return type:

any

get_docstring()

Get global docstring.

class pyrevit.coreutils.Timer

Bases: object

Timer class using python native time module.

Example

>>> timer = Timer()
>>> timer.get_time()
12
get_time()

Get Elapsed Time.

restart()

Restart Timer.

pyrevit.coreutils.calculate_dir_hash(dir_path, dir_filter, file_filter)

Create a unique hash to represent state of directory.

Parameters:
  • dir_path (str) – target directory
  • dir_filter (str) – exclude directories matching this regex
  • file_filter (str) – exclude files matching this regex
Returns:

hash value as string

Return type:

str

Example

>>> calculate_dir_hash(source_path, '\.extension', '\.json')
"1a885a0cae99f53d6088b9f7cee3bf4d"
pyrevit.coreutils.can_access_url(url_to_open, timeout=1000)

Check if url is accessible within timeout.

Parameters:
  • url_to_open (str) – url to check access for
  • timeout (int) – timeout in milliseconds
Returns:

true if accessible

Return type:

bool

pyrevit.coreutils.check_internet_connection(timeout=1000)

Check if internet connection is available.

Pings a few well-known websites to check if internet connection is present.

Parameters:timeout (int) – timeout in milliseconds
Returns:url if internet connection is present, None if no internet.
pyrevit.coreutils.check_revittxt_encoding(filename)

Check if given file is in UTF-16 (UCS-2 LE) encoding.

Parameters:filename (str) – file path
pyrevit.coreutils.check_utf8bom_encoding(filename)

Check if given file is in UTF-8 encoding.

Parameters:filename (str) – file path
pyrevit.coreutils.cleanup_filename(file_name, windows_safe=False)

Cleanup file name from special characters.

Parameters:file_name (str) – file name
Returns:cleaned up file name
Return type:str

Example

>>> cleanup_filename('Myfile-(3).txt')
"Myfile(3).txt"
>>> cleanup_filename('Perforations 1/8" (New)')
"Perforations 18 (New).txt"
pyrevit.coreutils.cleanup_string(input_str, skip=None)

Replace special characters in string with another string.

This function was created to help cleanup pyRevit command unique names from any special characters so C# class names can be created based on those unique names.

coreutils.SPECIAL_CHARS is the conversion table for this function.

Parameters:input_str (str) – input string to be cleaned

Example

>>> src_str = 'TEST@Some*<value>'
>>> cleanup_string(src_str)
"TESTATSomeSTARvalue"
pyrevit.coreutils.correct_revittxt_encoding(filename)

Convert encoding of text file generated by Revit to UTF-8.

Parameters:filename (str) – file path
pyrevit.coreutils.current_date()

Return formatted current date.

Current implementation uses %Y-%m-%d to format date.

Returns:formatted current date.
Return type:str

Example

>>> current_date()
'2018-01-03'
pyrevit.coreutils.current_time()

Return formatted current time.

Current implementation uses %H:%M:%S to format time.

Returns:formatted current time.
Return type:str

Example

>>> current_time()
'07:50:53'
pyrevit.coreutils.decrement_str(input_str, step=1, shrink=False)

Decrement identifier.

Parameters:
  • input_str (str) – identifier e.g. A310a
  • step (int) – number of steps to change the identifier
Returns:

modified identifier

Return type:

str

Example

>>> decrement_str('A310a')
'A309z'
pyrevit.coreutils.dletter_to_unc(dletter_path)

Convert drive letter path into UNC path of that drive.

Parameters:dletter_path (str) – drive letter path
Returns:UNC path
Return type:str

Example

>>> # assuming J: is mapped to //filestore/server/jdrive
>>> dletter_to_unc('J:/somefile.txt')
'//filestore/server/jdrive/somefile.txt'
pyrevit.coreutils.extend_counter(input_str, upper=True, use_zero=False)

Add a new level to identifier. e.g. A310 -> A310A

Parameters:
  • input_str (str) – identifier e.g. A310
  • upper (bool) – use UPPERCASE characters for extension
  • use_zero (bool) – start from 0 for numeric extension
Returns:

extended identifier

Return type:

str

Example

>>> extend_counter('A310')
'A310A'
>>> extend_counter('A310A', use_zero=True)
'A310A0'
pyrevit.coreutils.extract_guid(source_str)

Extract GUID number from a string.

pyrevit.coreutils.extract_range(formatted_str, max_range=500)

Extract range from formatted string.

String must be formatted as below A103 No range A103-A106 A103 to A106 A103:A106 A103 to A106 A103,A105a A103 and A105a A103;A105a A103 and A105a

Parameters:formatted_str (str) – string specifying range
Returns:list of names in the specified range
Return type:list

Example

>>> exract_range('A103:A106')
['A103', 'A104', 'A105', 'A106']
>>> exract_range('S203-S206')
['S203', 'S204', 'S205', 'S206']
>>> exract_range('M00A,M00B')
['M00A', 'M00B']
pyrevit.coreutils.filter_null_items(src_list)

Remove None items in the given list.

Parameters:src_list (list) – list of any items
Returns:cleaned list
Return type:list
pyrevit.coreutils.format_hex_rgb(rgb_value)

Formats rgb value as #RGB value string.

pyrevit.coreutils.fully_remove_dir(dir_path)

Remove directory recursively.

Parameters:dir_path (str) – directory path
pyrevit.coreutils.fuzzy_search_ratio(target_string, sfilter, regex=False)

Match target string against the filter and return a match ratio.

Parameters:
  • target_string (str) – target string
  • sfilter (str) – search term
  • regex (bool) – treat the sfilter as regular expression pattern
Returns:

integer between 0 to 100, with 100 being the exact match

Return type:

int

pyrevit.coreutils.get_all_subclasses(parent_classes)

Return all subclasses of a python class.

Parameters:parent_classes (list) – list of python classes
Returns:list of python subclasses
Return type:list
pyrevit.coreutils.get_canonical_parts(canonical_string)

Splots argument using dot, returning all composing parts.

Parameters:canonical_string (str) – Source string e.g. “Config.SubConfig”
Returns:list of composing parts
Return type:list[str]

Example

>>> get_canonical_parts("Config.SubConfig")
['Config', 'SubConfig']
pyrevit.coreutils.get_enum_none(enum_type)

Returns the None value in given Enum.

pyrevit.coreutils.get_enum_value(enum_type, value_string)

Return enum value matching given value string (case insensitive)

pyrevit.coreutils.get_enum_values(enum_type)

Returns enum values.

pyrevit.coreutils.get_exe_version(exepath)

Extract Product Version value from EXE file.

pyrevit.coreutils.get_file_name(file_path)

Return file basename of the given file.

Parameters:file_path (str) – file path
pyrevit.coreutils.get_integer_length(number)

Return digit length of given number.

pyrevit.coreutils.get_mapped_drives_dict()

Return a dictionary of currently mapped network drives.

pyrevit.coreutils.get_my_ip()

Return local ip address of this machine

pyrevit.coreutils.get_paper_sizes(printer_name=None)

Get paper sizes defined on this system

Returns:list of papersize instances
Return type:list[]
pyrevit.coreutils.get_reg_key(key, subkey)

Get value of the given Windows registry key and subkey.

Parameters:
  • key (PyHKEY) – parent registry key
  • subkey (str) – subkey path
Returns:

registry key if found, None if not found

Return type:

PyHKEY

Example

>>> get_reg_key(wr.HKEY_CURRENT_USER, 'Control Panel/International')
... <PyHKEY at 0x...>
pyrevit.coreutils.get_revit_instance_count()

Return number of open host app instances.

Returns:number of open host app instances.
Return type:int
pyrevit.coreutils.get_str_hash(source_str)

Calculate hash value of given string.

Current implementation uses hashlib.md5() hash function.

Parameters:source_str (str) – source str
Returns:hash value as string
Return type:str
pyrevit.coreutils.get_sub_folders(search_folder)

Get a list of all subfolders directly inside provided folder.

Parameters:search_folder (str) – folder path
Returns:list of subfolder names
Return type:list
pyrevit.coreutils.has_nonprintable(input_str)

Check input string for non-printable characters.

Parameters:input_str (str) – input string
Returns:True if contains non-printable characters
Return type:bool
pyrevit.coreutils.hex2int_long(hex_string)

Hexadecimal string to Integer.

pyrevit.coreutils.increment_str(input_str, step=1, expand=False)

Incremenet identifier.

Parameters:
  • input_str (str) – identifier e.g. A310a
  • step (int) – number of steps to change the identifier
Returns:

modified identifier

Return type:

str

Example

>>> increment_str('A319z')
'A320a'
pyrevit.coreutils.inspect_calling_scope_global_var(variable_name)

Trace back the stack to find the variable in the caller global stack.

Parameters:variable_name (str) – variable name to look up in caller global scope
pyrevit.coreutils.inspect_calling_scope_local_var(variable_name)

Trace back the stack to find the variable in the caller local stack.

PyRevitLoader defines __revit__ in builtins and __window__ in locals. Thus, modules have access to __revit__ but not to __window__. This function is used to find __window__ in the caller stack.

Parameters:variable_name (str) – variable name to look up in caller local scope
pyrevit.coreutils.int2hex_long(number)

Integer to hexadecimal string.

pyrevit.coreutils.is_blank(input_string)

Check if input string is blank (multiple white spaces is blank).

Parameters:input_string (str) – input string
Returns:True if string is blank
Return type:bool

Example

>>> is_blank('   ')
True
pyrevit.coreutils.is_box_visible_on_screens(left, top, width, height)

Check if given box is visible on any screen.

pyrevit.coreutils.is_url_valid(url_string)

Check if given URL is in valid format.

Parameters:url_string (str) – URL string
Returns:True if URL is in valid format
Return type:bool

Example

>>> is_url_valid('https://www.google.com')
True
pyrevit.coreutils.join_strings(str_list, separator=';')

Join strings using provided separator.

Parameters:
  • str_list (list) – list of string values
  • separator (str) – single separator character, defaults to DEFAULT_SEPARATOR
Returns:

joined string

Return type:

str

pyrevit.coreutils.kill_tasks(task_name)

Kill running tasks matching task_name

Parameters:task_name (str) – task name

Example

>>> kill_tasks('Revit.exe')
pyrevit.coreutils.make_canonical_name(*args)

Join arguments with dot creating a unique id.

Parameters:*args – Variable length argument list of type str
Returns:dot separated unique name
Return type:str

Example

>>> make_canonical_name('somename', 'someid', 'txt')
"somename.someid.txt"
pyrevit.coreutils.new_uuid()

Create a new UUID (using dotnet Guid.NewGuid)

pyrevit.coreutils.open_folder_in_explorer(folder_path)

Open given folder in Windows Explorer.

Parameters:folder_path (str) – directory path
pyrevit.coreutils.prepare_html_str(input_string)

Reformat html string and prepare for pyRevit output window.

pyRevit output window renders html content. But this means that < and > characters in outputs from python (e.g. <class at xxx>) will be treated as html tags. To avoid this, all <> characters that are defining html content need to be replaced with special phrases. pyRevit output later translates these phrases back in to < and >. That is how pyRevit distinquishes between <> printed from python and <> that define html.

Parameters:input_string (str) – input html string

Example

>>> prepare_html_str('<p>Some text</p>')
"&clt;p&cgt;Some text&clt;/p&cgt;"
pyrevit.coreutils.random_alpha()

Return a random alpha value (between 0 and 1.00).

pyrevit.coreutils.random_color()

Return a random color channel value (between 0 and 255).

pyrevit.coreutils.random_hex_color()

Return a random color in hex format.

Example

>>> random_hex_color()
'#FF0000'
pyrevit.coreutils.random_rgb_color()

Return a random color in rgb format.

Example

>>> random_rgb_color()
'rgb(255, 0, 0)'
pyrevit.coreutils.random_rgba_color()

Return a random color in rgba format.

Example

>>> random_rgba_color()
'rgba(255, 0, 0, 0.5)'
pyrevit.coreutils.read_source_file(source_file_path)

Read text file and return contents.

Parameters:source_file_path (str) – target file path
Returns:file contents
Return type:str
Raises:PyRevitException on read error
pyrevit.coreutils.read_url(url_to_open)

Get the url and return response.

Parameters:url_to_open (str) – url to check access for
pyrevit.coreutils.reformat_string(orig_str, orig_format, new_format)

Reformat a string into a new format.

Extracts information from a string based on a given pattern, and recreates a new string based on the given new pattern.

Parameters:
  • orig_str (str) – Original string to be reformatted
  • orig_format (str) – Pattern of the original str (data to be extracted)
  • new_format (str) – New pattern (how to recompose the data)
Returns:

Reformatted string

Return type:

str

Example

>>> reformat_string('150 - FLOOR/CEILING - WD - 1 HR - FLOOR ASSEMBLY',
                    '{section} - {loc} - {mat} - {rating} - {name}',
                    '{section}:{mat}:{rating} - {name} ({loc})'))
'150:WD:1 HR - FLOOR ASSEMBLY (FLOOR/CEILING)'
pyrevit.coreutils.reverse_dict(input_dict)

Reverse the key, value pairs.

Parameters:input_dict (dict) – source ordered dict
Returns:reversed dictionary
Return type:defaultdict

Example

>>> reverse_dict({1: 2, 3: 4})
defaultdict(<type 'list'>, {2: [1], 4: [3]})
pyrevit.coreutils.reverse_html(input_html)

Reformat codified pyRevit output html string back to normal html.

pyRevit output window renders html content. But this means that < and > characters in outputs from python (e.g. <class at xxx>) will be treated as html tags. To avoid this, all <> characters that are defining html content need to be replaced with special phrases. pyRevit output later translates these phrases back in to < and >. That is how pyRevit distinquishes between <> printed from python and <> that define html.

Parameters:input_html (str) – input codified html string

Example

>>> prepare_html_str('&clt;p&cgt;Some text&clt;/p&cgt;')
"<p>Some text</p>"
pyrevit.coreutils.run_process(proc, cwd='C:')

Run shell process silently.

Parameters:
  • proc (str) – process executive name
  • cwd (str) – current working directory
Exmaple:
>>> run_process('notepad.exe', 'c:/')
pyrevit.coreutils.show_entry_in_explorer(entry_path)

Show given entry in Windows Explorer.

Parameters:entry_path (str) – directory or file path
pyrevit.coreutils.split_words(input_string)

Splits given string by uppercase characters

Parameters:input_string (str) – input string
Returns:split string
Return type:list[str]

Example

>>> split_words("UIApplication_ApplicationClosing")
... ['UIApplication', 'Application', 'Closing']
pyrevit.coreutils.timestamp()

Return timestamp for current time.

Returns:timestamp in string format
Return type:str

Example

>>> timestamp()
'01003075032506808'
pyrevit.coreutils.touch(fname, times=None)

Update the timestamp on the given file.

Parameters:
  • fname (str) – target file path
  • times (int) – number of times to touch the file
pyrevit.coreutils.unc_to_dletter(unc_path)

Convert UNC path into drive letter path.

Parameters:unc_path (str) – UNC path
Returns:drive letter path
Return type:str

Example

>>> # assuming J: is mapped to //filestore/server/jdrive
>>> unc_to_dletter('//filestore/server/jdrive/somefile.txt')
'J:/somefile.txt'
pyrevit.coreutils.verify_directory(folder)

Check if the folder exists and if not create the folder.

Parameters:folder (str) – path of folder to verify
Returns:path of verified folder, equals to provided folder
Return type:str
Raises:OSError on folder creation error.