Sample Code Revit Batch Processor 1.1.11 documentation

Contents:

This Page

duHast.Utilities package

Subpackages

Submodules

duHast.Utilities.batch_processor_log_utils module

Helper functions to process Revit BatchProcessor log files.

duHast.Utilities.batch_processor_log_utils.debug_mode_ = False

global variable controlling debug output

duHast.Utilities.batch_processor_log_utils.EXCEPTION_MESSAGES = ['ERROR: An error occurred while executing the task script! Operation', 'WARNING: Timed-out', 'Exception: [Exception]', '\t- \tMessage: An unrecoverable error has occurred.  The program will now be terminated.', 'Script Exception:']

Message snippets which indicate processing of a file went bad

duHast.Utilities.batch_processor_log_utils.output(message='')
duHast.Utilities.batch_processor_log_utils.delete_log_data_files(directory_path)

Deletes all log marker files in a directory.

Parameters:

directory_path (str) – The directory path containing marker files to be deleted.

Returns:

True if all files where deleted successfully, otherwise False.

Return type:

bool

duHast.Utilities.batch_processor_log_utils.adjust_session_id_for_file_name(id)

Removes chevrons and replace colons with underscores in session id supplied by revit batch processor so it can be used in a file name.

Parameters:

id (str) – Session id supplied by revit batch processor.

Returns:

Re-formatted session id.

Return type:

str

duHast.Utilities.batch_processor_log_utils.adjust_session_id_file_name_back(file_name_id)

Re-introduces chevrons and replaces underscores with colons to match session Id format used in batch processor to a file name using a batch processor supplied id.

Parameters:

file_name_id (str) – A file name containing a session id with all illegal characters replaced.

Returns:

A session id.

Return type:

str

duHast.Utilities.batch_processor_log_utils.write_session_id_marker_file(folder_path, session_id)

Writes out an empty marker file in given directory.

  • File is of type .txt

  • File name is the batch processor session_id used to identify the log file belonging to this process.

Parameters:
  • folder_path (str) – Directory of where the file will be written to.

  • session_id (str) – Session id supplied by revit batch processor.

Returns:

True if marker file was written successfully, otherwise False.

Return type:

bool

duHast.Utilities.batch_processor_log_utils.get_current_session_ids(folder_path, delete_marker_files=True)

Returns file names of all text files in a given directory representing session Ids.

Files will be deleted immediately after reading

Parameters:

folder_path (str) – Directory of where test files are located

Returns:

A list of ids in string format.

Return type:

[str]

duHast.Utilities.batch_processor_log_utils.get_log_files(list_of_session_ids)

Returns a list of fully qualified filepath to log files matching the provided session Ids.

Parameters:

list_of_session_ids ([str]) – List of session ids.

Returns:

List of fully qualified file path.

Return type:

[str]

duHast.Utilities.batch_processor_log_utils.get_session_id_from_log_file(file_path)

Reads the first two rows of a log file to get the session Id used.

Parameters:

file_path (str) – Fully qualified file path to log file

Returns:

The session id, or if not not a log file: an empty string.

Return type:

str

duHast.Utilities.batch_processor_log_utils.get_id_from_row(row)

Extracts the session Id from logfile row.

sample: {“date”:{“local”:”17/12/2020”,”utc”:”17/12/2020”},”time”:{“local”:”16:49:27”,”utc”:”05:49:27”},”sessionId”:”235e2180-dc33-4d61-8773-1005a59344c0”,”message”:{“msgId”:””,”message”:”Session ID: <2020-12-17T05:49:27.559Z>”}}

Note: There are two session id fields in thi string!

TODO: Do some error handling!

Parameters:

row (str) – A json formatted string with the session id in chevrons.

Returns:

The session id.

Return type:

str

duHast.Utilities.batch_processor_log_utils.get_text_between(text, first, last)

Returns text in between characters

Parameters:
  • text (str) – Text to parse

  • first (str) – String indicating start

  • last (str) – String indicating end

Returns:

string in between start and end.

Return type:

str

duHast.Utilities.batch_processor_log_utils.get_message_from_json(data)

Returns the outer message string from json formatted message field in log file.

sample: {“date”:{“local”:”17/12/2020”,”utc”:”17/12/2020”},”time”:{“local”:”16:49:27”,”utc”:”05:49:27”},”sessionId”:”235e2180-dc33-4d61-8773-1005a59344c0”,”message”:{“msgId”:””,”message”:”Session ID: <2020-12-17T05:49:27.559Z>”}}

This includes leading tab characters

Parameters:

data (str) – json formatted row of logfile

Returns:

The message string

Return type:

str

duHast.Utilities.batch_processor_log_utils.process_log_file(file_path)

Process revit batch processor session log file.

  • find Revit files processed:

  • check whether an exception occurred when processing any of the above files.

Parameters:

file_path (str) – Fully qualified file path to json formatted log file

Returns:

returns list of arrays in format: [[processed Revit file name, status of processing (true or false), message]]

Return type:

[[str]]

duHast.Utilities.batch_processor_log_utils.filter_files_not_found(files_processed, files_not_found)
duHast.Utilities.batch_processor_log_utils.get_process_status(file_to_check, log_file_path)

Reads a log file and checks whether any exception occurred when processing a specific revit file.

Parameters:
  • file_to_check (str) – Fully qualified file path of Revit file which was processed

  • log_file_path (str) – The fully qualified batch processor session log file path.

Returns:

A process status and a message.

  • process status: True if no exception occurred during revit file processing, otherwise false

  • message: the exception message recorded in the log file.

Return type:

bool, str

duHast.Utilities.batch_processor_log_utils.get_file_name_from_data_block(message_block)

Extracts the file name from a process message block.

Parameters:

message_block ([str]) – list of json formatted rows representing all messages received during file process

Returns:

The fully qualified file path of the file processed

Return type:

str

duHast.Utilities.batch_processor_log_utils.get_files_processed(file_path)

Reads a batch processor logfile and extracts all file names of files processed.

Parameters:

file_path (str) – The fully qualified file path to log file.

Returns:

a list lists containing The fully qualified file path for each file processed and their process status. True for no exception encountered, otherwise false. [[filepath, status]]

Return type:

[[str, bool]]

duHast.Utilities.batch_processor_log_utils.get_file_data(data)
duHast.Utilities.batch_processor_log_utils.get_files_not_found(files_processed)

Filters list of all files meant to be processed and returns the ones flagged as file not found.

Parameters:

files_processed ([[str, bool]]) – array of lists in format: [[filename, status as bool],[filename, status as bool],…]

Returns:

array of lists in format: [[filename, status as bool],[filename, status as bool],…]

Return type:

[[str, bool]]

duHast.Utilities.batch_processor_log_utils.get_log_blocks(json_data, start_marker, end_markers, multiple_blocks)

Reads json formatted data into blocks per files processed.

Returns the message sections per row entry only.

Parameters:
  • json_data ([str]) – List of logfile rows in json data format

  • start_marker (str) – String in messages indicating start of block.

  • end_markers (str) – String in messages indicating end of block.

  • multiple_blocks (bool) – Flag indicating whether there are multiple data block in log file to be returned

Returns:

List of list of str

Return type:

[[str]]

duHast.Utilities.batch_processor_log_utils.read_log_file(file_path)

Reads batch processor log file into lists of json objects.

Sample row:

{‘sessionId’: ‘778e87a5-4b94-4552-9e7e-c9ed38b5caee’, ‘time’: {‘local’: ‘09:35:45’, ‘utc’: ‘22:35:45’}, ‘date’: {‘local’: ‘25/11/2020’, ‘utc’: ‘24/11/2020’}, ‘message’: {‘msgId’: ‘’, ‘message’: ‘’}}

Parameters:

file_path (str) – The fully qualified file path to log file in json format

Returns:

list of json objects

Return type:

[json]

duHast.Utilities.batch_processor_log_utils.process_log_files(folder_path, debug=False)

Loops over log files and checks whether any exceptions occurred during revit files processing.

Parameters:
  • folder_path (str) – Fully qualified directory path where marker files are stored.

  • debug (bool, optional) – Flag indicating whether this is running in debug mode which will output some debug messages, defaults to False

Returns:

Result class instance.

  • Process status returned in result.status. False if an exception occurred, otherwise True.

  • result.message will contain message(s) for each revit file found in logs and whether an exception occurred during processing

  • result.result will be an empty list.

On exception:

  • result.status (bool) will be False.

  • result.message will contain the exception message.

  • result.status will be an empty list.

Return type:

Result

duHast.Utilities.benchmarking module

Helper functions for benchmarking:.

  • two values

  • whether a text value starts or does not start with a given text value

duHast.Utilities.benchmarking.measure_time_wrapper(func, logger=None, measure=True)
duHast.Utilities.benchmarking.add_measure_time(func, should_output=True)

Decorator function to measure the time a function takes to execute and then print it to the console.

Use like @measure_time(should_output = show_benchmarking_output_bool) def function_to_measure():

Parameters:

should_output (bool) – Whether the elapsed time should be printed to the console

duHast.Utilities.compare module

Helper functions relating to comparing:.

  • two values

  • whether a text value starts or does not start with a given text value

duHast.Utilities.compare.does_not_equal(valueOne, valueTwo)

Returns True if valueOne does not match valueTwo. :param valueOne: a value :type valueOne: var :param valueTwo: another value :type valueTwo: var :return: True if valueOne does not match valueTwo, otherwise False :rtype: bool

duHast.Utilities.compare.does_equal(valueOne, valueTwo)

Returns True if valueOne does match valueTwo. :param valueOne: a value :type valueOne: var :param valueTwo: another value :type valueTwo: var :return: True if valueOne does match valueTwo, otherwise False :rtype: bool

duHast.Utilities.compare.one_start_with_two(valueOne, valueTwo)

Returns True if valueOne starts with valueTwo. :param valueOne: a value :type valueOne: str :param valueTwo: another value :type valueTwo: str :return: True if valueOne starts with valueTwo, otherwise False :rtype: bool

duHast.Utilities.compare.two_does_not_start_with_one(valueOne, valueTwo)

Returns True if valueTwo does not starts with valueOne. :param valueOne: a value :type valueOne: str :param valueTwo: another value :type valueTwo: str :return: True if valueTwo does not starts with valueOne, otherwise False :rtype: bool

duHast.Utilities.compare.is_close(a, b, rel_tol=1e-09, abs_tol=0.0)

Compares two floats with a tolerance. Returns True if they are close enough, otherwise False

refer to: https://stackoverflow.com/questions/5595425/what-is-the-best-way-to-compare-floats-for-almost-equality-in-python

Parameters:
  • a (float) – A float

  • b (float) – A float

  • rel_tol (float, optional) – Relative tolerance used to compare the two floats, defaults to 1e-09

  • abs_tol (float, optional) – Absolute tolerance used to compare the two floats, defaults to 0.0

Returns:

Returns True if they are close enough to be considered equal, otherwise False

Return type:

bool

duHast.Utilities.console_out module

A function used to output messages to a console.

duHast.Utilities.console_out.default_out_print(message)

Default pip out method: print to console.

Parameters:

message (str) – A message

duHast.Utilities.console_out.output(message='', pipe_out=<function default_out_print>)

Print message to pipe.

Note:

  • If message is not a string it will convert it to a string.

  • Multi line strings will pe printed line by line.

  • strings containing [true] ot [false] will be padded to have [true] or [false] to the right hand side.

Parameters:

message (str, optional) – The message, defaults to ‘’

duHast.Utilities.console_out.output_with_time_stamp(message='', pipe_out=<function default_out_print>)

Print message to console.

Note:

  • The message will be prefixed with a date stamp in format ‘2022-08-09 19_09_19 :’

  • If message is not a string it will convert it to a string.

  • Multi line strings will pe printed line by line

  • strings containing [true] ot [false] will be padded to have [true] or [false] to the right hand side.

Parameters:

message (str, optional) – The message, defaults to ‘’

duHast.Utilities.console_out.output_header(message='', pipe_out=<function default_out_print>)

Prints header message to pipe.

Note:

  • If message is not a string it will convert it to a string.

Parameters:

message (str, optional) – The message, defaults to ‘’

duHast.Utilities.console_out.output_header_with_time_stamp(message='', pipe_out=<function default_out_print>)

Prints header message to pipe.

Note:

  • If message is not a string it will convert it to a string.

  • The header will be prefixed with a date stamp in format ‘2022-08-09 19_09_19 :’

Parameters:

message (str, optional) – The message, defaults to ‘’

duHast.Utilities.date_stamps module

This module contains a number of helper functions relating to:

  • date stamps (with varies formatting options)

duHast.Utilities.date_stamps.FILE_DATE_STAMP_YYMMDD_SPACE = '%y %m %d'

file stamp date format using spaces as delimiter: 21 03 01

duHast.Utilities.date_stamps.FILE_DATE_STAMP_YYYYMMDD_SPACE = '%Y %m %d'

file stamp date format using spaces as delimiter: 2021 03 01

duHast.Utilities.date_stamps.FILE_DATE_STAMP_YYYY_MM_DD = '%Y_%m_%d'

file stamp date format using underscores as delimiter: 2021_03_01

duHast.Utilities.date_stamps.FILE_DATE_STAMP_YYYY_MM_DD_HH_MM_SEC = '%Y_%m_%d_%H_%M_%S'

file stamp date time format using underscores as delimiter: 2021_03_01_18_59_59

duHast.Utilities.date_stamps.TIME_STAMP_HHMMSEC_COLON = '%H:%M:%S'

time stamp using colons: 18:59:59

duHast.Utilities.date_stamps.TIME_STAMP_HHMMSEC_UNDERSCORE = '%H_%M_%S'

time stamp using colons: 18_59_59

duHast.Utilities.date_stamps.get_file_date_stamp(format='%y_%m_%d')

Returns a date stamp formatted suitable for a file name. :param format: The date stamp format, defaults to FILE_DATE_STAMP_YY_MM_DD :type format: str, optional :return: datetime.now() string formatted using supplied format string :rtype: str

duHast.Utilities.date_stamps.FOLDER_DATE_STAMP_YYMMDD = '%y%m%d'

folder date format: no delimiter 210301

duHast.Utilities.date_stamps.FOLDER_DATE_STAMP_YYYYMMDD = '%Y%m%d'

folder date format: no delimiter 20210301

duHast.Utilities.date_stamps.FOLDER_DATE_STAMP_YYYY = '%Y'

folder date format: no delimiter 2021

duHast.Utilities.date_stamps.get_folder_date_stamp(format='%Y%m%d')

Returns a date stamp formatted suitable for a folder name. :param format: The date stamp format, defaults to FOLDER_DATE_STAMP_YYYYMMDD :type format: str, optional :return: datetime.now() string formatted using supplied format string :rtype: str

duHast.Utilities.date_stamps.get_date_stamp(format)

Returns a date stamp formatted using past in format string. :param format: The date stamp format :type format: str :return: datetime.now() string formatted using supplied format string :rtype: str

duHast.Utilities.date_stamps.get_date_stamped_file_name(file_path, file_extension='.txt', file_suffix='')

Returns a time stamped output file name based on the past in file name and file extension. :param file_path: Fully qualified file path to file :type file_path: str :param file_extension: File extension needs to include ‘.’, defaults to ‘.txt’ :type file_extension: str, optional :param file_suffix: File suffix will be appended after the name but before the file extension, defaults to ‘’ :type file_suffix: str, optional :return: File name. :rtype: str

duHast.Utilities.directory_io module

Helper functions relating to directory IO .

duHast.Utilities.directory_io.is_directory(directory_path)

Check if a given path is a directory :param directory_path: Fully qualified directory path :type directory_path: str :return: True if directory, otherwise False :rtype: bool

duHast.Utilities.directory_io.directory_empty_delete(full_directory_path)

Deletes an empty directory :param full_directory_path: Path to directory :type full_directory_path: str :return: True directory deleted, otherwise False :rtype: bool

duHast.Utilities.directory_io.directory_delete(full_directory_path)

Deletes a directory (even if it contains files) :param full_directory_path: Path to directory :type full_directory_path: str :return: True directory deleted, otherwise False :rtype: bool

duHast.Utilities.directory_io.get_child_directories(full_directory_path)

Returns the immediate subdirectories of directory :param full_directory_path: Path to directory :type full_directory_path: str :return: any sub directories, empty list if none exist :rtype: list of str

duHast.Utilities.directory_io.get_parent_directory(full_directory_path)

Returns the parent directory of directory, or empty string if invalid directory :param full_directory_path: Path to directory :type full_directory_path: str :return: parent directory, or empty string :rtype: str

duHast.Utilities.directory_io.create_directory(root, folder_name)

Create a folder. :param root: Directory path in which the new folder is to be created :type root: str :param folder_name: New folder name. :type folder_name: str :return: True if folder is created, otherwise False :rtype: bool

duHast.Utilities.directory_io.create_target_directory(root_path, folder_name)

Create a folder. Checks whether folder exists and if not attempts to create it.

Parameters:
  • root (str) – Directory path in which the new folder is to be created

  • folder_name (str) – New folder name.

Returns:

True if folder is created, otherwise False

Return type:

bool

duHast.Utilities.directory_io.directory_exists(directory_path)

Check if a given directory exists :param directory_path: Fully qualified directory path :type directory_path: str :return: True if directory exists, otherwise False :rtype: bool

duHast.Utilities.files_base module

Helper functions relating to text files.

duHast.Utilities.files_base.write_report_data(file_name, header, data, write_type='w', enforce_ascii=False, encoding='utf-8', bom=None, quoting=3, delimiter=',')

Function writing out report information as CSV file. :param file_name: The reports fully qualified file path. :type file_name: str :param header: list of column headers :type header: list of str :param data: list of list of strings representing row data :type data: [[str,str,..]] :param write_type: Flag indicating whether existing report file is to be overwritten ‘w’ or appended to ‘a’, defaults to ‘w’ :type write_type: str, optional :param enforce_ascci: Flag to enforce ASCII encoding on data. If True, data will be encoded to ASCII. Defaults to False. :type enforce_ascci: bool, optional :param encoding: Encoding used to write the file. Defaults to ‘utf-8’. :type encoding: str, optional :param bom: the byte order mark, Default is None (none will be written). BOM: “utf-16” = , “utf-16-le” = , utf-8 = :type bom: str, default is NoneType :param quoting: Quoting style used by the csv writer. Defaults to csv.QUOTE_NONE. Options are csv.QUOTE_ALL, csv.QUOTE_MINIMAL, csv.QUOTE_NONNUMERIC, csv.QUOTE_NONE :type quoting: int, optional

Returns:

A Result object, with the result attribute set to True if the file was written successfully, False otherwise.

Return type:

Result

duHast.Utilities.files_base.read_column_based_text_file_with_encoding(file_path, increase_max_field_size_limit=False, delimiter=',')

Read a column based text file, attempting to detect and handle encoding, including BOMs.

Parameters:
  • file_path (str) – The fully qualified file path to the csv file.

  • increase_max_field_size_limit (bool, optional) – Flag to increase the max field size limit. Defaults to False.

  • delimiter (str, optional) – The delimiter used in the text file. Defaults to ‘,’.

Returns:

A Result object, with the result attribute set to a list of list of strings representing the data in each row.

Return type:

Result

duHast.Utilities.files_base.process_txt_file(file_path, delimiter=',')

Process a txt file by removing null bytes and then reading its content.

Parameters:
  • file_path (str) – The path to the CSV file to be processed.

  • delimiter (str, optional) – The delimiter used in the text file. Defaults to ‘,’.

Returns:

A Result object, with the result attribute set to a list of list of strings representing the data in each row.

Return type:

:class:`.Result

duHast.Utilities.files_base.read_column_based_text_file(file_path, increase_max_field_size_limit=False, delimiter=',')

Read a csv file into a list of rows, where each row is another list.

Attempts to read the file with encoding first, then without encoding if that fails. Encoding is attempted first because it is more likely to be successful. The following encodings are attempted: ‘utf-8-sig’, ‘utf-16’.

Parameters:
  • file_path (str) – The fully qualified file path to the csv file.

  • increase_max_field_size_limit (bool, optional) – Flag to increase the max field size limit. Defaults to False.

  • delimiter (str, optional) – The delimiter used in the text file. Defaults to ‘,’.

Returns:

A Result object, with the result attribute set to a list of list of strings representing the data in each row.

Return type:

Result

duHast.Utilities.files_base.get_first_row_in_column_based_text_file(file_path, delimiter=',')

Reads the first line of a column based text file and returns it as a list of strings.

Parameters:
  • file_path (str) – The fully qualified file path.

  • delimiter (str, optional) – The delimiter used in the text file. Defaults to ‘,’.

  • encoding (str, optional) – Encoding used to read the file. Defaults to ‘utf-8’.

Returns:

A Result object, with the first row of a text file in its result attribute.

Return type:

Result

duHast.Utilities.files_combine module

Helper functions relating to combining text files.

duHast.Utilities.files_combine.combine_files(folder_path, file_prefix='', file_suffix='', file_extension='.txt', output_file_name='result.txt', file_getter=<function get_files_single_directory>, delimiter=', ', quoting=0)

Combines multiple text files into a single new file. Assumes:

  • files have a header row followed by data rows

  • same number of headers (columns) in each files.

  • files have the same header names per column

  • files are encoded in UTF-8!

The new file will be saved into the same folder as the original files.

Parameters:
  • folder_path (str) – Folder path from which to get files to be combined and to which the combined file will be saved.

  • file_prefix (str) – Filter: File name starts with this value

  • file_suffix (str) – Filter: File name ends with this value.

  • file_extension (str, format '.extension') – Filter: File needs to have this file extension

  • output_file_name (str, optional) – The file name of the combined file, defaults to ‘result.txt’

  • file_getter (func(folder_path, file_prefix, file_suffix, file_extension), optional) – Function returning list of files to be combined, defaults to GetFilesSingleFolder

  • delimiter (str, optional) – The delimiter used in the files (e.g., ‘,’ for CSV, ‘ ‘ for tab-separated), defaults to ‘,’

  • quoting (int, optional) – The quoting option for the CSV writer, defaults to csv.QUOTE_MINIMAL

Returns:

A result object with status and message.

Return type:

Result

duHast.Utilities.files_combine.append_to_file(source_file, append_file, ignore_first_row=False, delimiter=',', quoting=0)

Appends one text file to another.

Assumes:

  • same number of headers (columns) in both files.

  • files are encoded in UTF-8!

Parameters:
  • source_file (str) – The fully qualified file path of the file to which the other file will be appended.

  • append_file (str) – The fully qualified file path of the file to be appended.

  • ignore_first_row (bool) – If True, first row of append file will not be appended to source file.( Assumed its a header row )

  • delimiter (str, optional) – The delimiter used in the files (e.g., ‘,’ for CSV, ‘ ‘ for tab-separated), defaults to ‘,’

  • quoting (int, optional) – The quoting option for the CSV writer, defaults to csv.QUOTE_MINIMAL

Returns:

A result object with status and message.

Return type:

Result

duHast.Utilities.files_combine.combine_files_header_independent(folder_path, file_prefix='', file_suffix='', file_extension='.txt', output_file_name='result.txt', overwrite_existing=False)

Used to combine report files into one file, files may have different number / named columns.

Columns which are unique to some files will have as a value ‘N/A’ in files where those columns do not exist. File need to use <tab> character as column separator

Parameters:
  • folder_path (str) – Folder path from which to get files to be combined and to which the combined file will be saved.

  • file_prefix (str) – Filter: File name starts with this value

  • file_suffix (str) – Filter: File name ends with this value.

  • file_extension (str, format '.extension') – Filter: File needs to have this file extension

  • out_put_file_name (str, optional) – The file name of the combined file, defaults to ‘result.txt’

  • overwrite_existing (bool, optional) – Will overwrite an existing output file if set to True, defaults to False ( append to existing output file)

duHast.Utilities.files_combine.combine_files_csv_header_independent(folder_path, file_prefix='', file_suffix='', file_extension='.txt', output_file_name='result.csv', overwrite_existing=False)

Used to combine report files into one file, files may have different number / named columns.

Columns which are unique to some files will have as a value ‘N/A’ in files where those columns do not exist. File need to use <,> character as column separator. (.CSV) Assumes all files have a header row!

Parameters:
  • folder_path (str) – Folder path from which to get files to be combined and to which the combined file will be saved.

  • file_prefix (str) – Filter: File name starts with this value

  • file_suffix (str) – Filter: File name ends with this value.

  • file_extension (str, format '.extension') – Filter: File needs to have this file extension

  • output_file_name (str, optional) – The file name of the combined file, defaults to ‘result.csv’

  • overwrite_existing (bool, optional) – Will overwrite an existing output file if set to True, defaults to False ( append to existing output file)

Returns:

A result object with status and message.

Return type:

Result

duHast.Utilities.files_combine.combine_files_json(folder_path, file_prefix='', file_suffix='', file_extension='.txt', output_file_name='result.txt', file_getter=<function get_files_single_directory>)

Combines multiple json formatted text files into a single json list formatted file, where each file is a list entry. Assumes:

  • each file can contain a single line json formatted string

The new file will be saved into the same folder as the original files.

Parameters:
  • folder_path (str) – Folder path from which to get files to be combined and to which the combined file will be saved.

  • file_prefix (str) – Filter: File name starts with this value

  • file_suffix (str) – Filter: File name ends with this value.

  • file_extension (str, format '.extension') – Filter: File needs to have this file extension

  • out_put_file_name (str, optional) – The file name of the combined file, defaults to ‘result.txt’

  • file_getter (func(folder_path, file_prefix, file_suffix, file_extension), optional) – Function returning list of files to be combined, defaults to GetFilesSingleFolder

duHast.Utilities.files_csv module

Helper functions relating to comma separated text files.

duHast.Utilities.files_csv.get_unique_headers(files)

Gets a list of alphabetically sorted headers retrieved from text files. Assumes:

  • first row in each file is the header row

  • headers are separated by <tab> character

Parameters:

files (list of str) – List of file path from which the headers are to be returned.

Returns:

List of headers.

Return type:

list of str

duHast.Utilities.files_csv.process_csv(file_path)

Process a CSV file by removing null bytes and then reading its content.

Parameters:

file_path (str) – The path to the CSV file to be processed.

duHast.Utilities.files_csv.read_csv_file_with_encoding(file_path_csv, increase_max_field_size_limit=False)

Read a csv file, attempting to detect and handle encoding, including BOMs.

Parameters:

filepathCSV (str) – The fully qualified file path to the csv file.

Returns:

A list of list of strings representing the data in each row.

Return type:

list of list of str

duHast.Utilities.files_csv.read_csv_file(filepathCSV, increaseMaxFieldSizeLimit=False)

Read a csv file into a list of rows, where each row is another list.

Parameters:

filepathCSV (str) – The fully qualified file path to the csv file.

Returns:

A list of list of strings representing the data in each row.

Return type:

list of list of str

duHast.Utilities.files_csv.get_first_row_in_csv_file(filePath)

Reads the first line of a csv text file and returns it as a list of strings :param filePath: The fully qualified file path. :type filePath: str :return: A Result object, with the result attribute set to True if the first row was retrieved successfully, False otherwise. :rtype: Result

duHast.Utilities.files_csv.write_report_data_as_csv(file_name, header, data, write_type='w', enforce_ascii=False, encoding='utf-8', bom=None, quoting=3, delimiter=',')

Function writing out report information as CSV file. :param file_name: The reports fully qualified file path. :type file_name: str :param header: list of column headers :type header: list of str :param data: list of list of strings representing row data :type data: [[str,str,..]] :param write_type: Flag indicating whether existing report file is to be overwritten ‘w’ or appended to ‘a’, defaults to ‘w’ :type write_type: str, optional :param enforce_ascci: Flag to enforce ASCII encoding on data. If True, data will be encoded to ASCII. Defaults to False. :type enforce_ascci: bool, optional :param encoding: Encoding used to write the file. Defaults to ‘utf-8’. :type encoding: str, optional :param bom: the byte order mark, Default is None (none will be written). BOM: “utf-16” = , “utf-16-le” = , utf-8 = :type bom: str, default is NoneType :param quoting: Quoting style used by the csv writer. Defaults to csv.QUOTE_NONE. Options are csv.QUOTE_ALL, csv.QUOTE_MINIMAL, csv.QUOTE_NONNUMERIC, csv.QUOTE_NONE :type quoting: int, optional

Returns:

A Result object, with the result attribute set to True if the file was written successfully, False otherwise.

Return type:

Result

duHast.Utilities.files_get module

Helper functions relating to retrieving file information.

duHast.Utilities.files_get.get_files_single_directory(folder_path, file_prefix, file_suffix, file_extension)

Get files from a folder filtered by file prefix, file suffix, file extension :param folder_path: Folder path from which to get files. :type folder_path: str :param file_prefix: Filter: File name starts with this value. :type file_prefix: str :param file_suffix: Filter: File name ends with this value. :type file_suffix: str :param file_extension: Filter: File needs to have this file extension :type file_extension: str, format ‘.extension’ :return: A list of all the files matching the supplied filters. :rtype: list str

duHast.Utilities.files_get.get_files_from_directory_walker_with_filters(folder_path, file_prefix, file_suffix, file_extension)

Returns a list of all files in directory and nested sub directories where file name matches filters value. :param folder_path: Root folder path from which to get files. :type folder_path: str :param file_prefix: Filter: File name starts with this value :type file_prefix: str :param file_suffix: Filter: File name ends with this value. :type file_suffix: str :param file_extension: Filter: File needs to have this file extension :type file_extension: str, format ‘.extension’ :return: A list of all the files matching the supplied filters. :rtype: list str

duHast.Utilities.files_get.get_files_from_directory_walker_with_filters_simple(folder_path, file_extension)

Returns a list of all files in directory and nested subdirectories where file name matches file extension filter value :param folder_path: Root folder path from which to get files. :type folder_path: str :param file_extension: Filter: File needs to have this file extension :type file_extension: str, format ‘.extension’ :return: A list of all the files matching the supplied filters. :rtype: list str

duHast.Utilities.files_get.files_as_dictionary(folder_path, file_prefix, file_suffix, file_extension, include_sub_dirs=False)

Returns a dictionary of all files in directory and nested subdirectories where file name contains filter value. - key file name without extension - values: list of directories where this file occurs (based on file name only!) Use case: check for duplicates by file name only

Parameters:
  • folder_path (str) – Root folder path from which to get files.

  • file_prefix (str) – Filter: File name starts with this value

  • file_suffix (str) – Filter: File name ends with this value.

  • file_extension (str, format '.extension') – Filter: File needs to have this file extension

  • include_sub_dirs (bool, optional) – If True subdirectories will be included in search for files, defaults to False

Returns:

A dictionary where the key is the file name without the file extension. Value is a list of fully qualified file path to instances of that file.

Return type:

dictionary key: str value: lit of str

duHast.Utilities.files_get.get_files(folder_path, file_extension='.rvt')

Gets a list of files from a given folder with a given file extension. (Returns the full path for each file!)

Parameters:
  • folder_path (str) – Folder path from which to get files to be combined and to which the combined file will be saved.

  • file_extension (str, optional) – Filter: File needs to have this file extension, defaults to ‘.rvt’

Returns:

List of file path

Return type:

list of str

duHast.Utilities.files_get.get_files_with_filter(folder_path, file_extension='.rvt', filter='*')

Gets a list of files from a given folder with a given file extension and a matching a file name filter. (Returns the full path for each file!)

Parameters:
  • folder_path (str) – Folder path from which to get files.

  • file_extension (str, optional) – Filter: File needs to have this file extension, defaults to ‘.rvt’

  • filter (str, optional) – File name filter (‘something*’), defaults to ‘*’

Returns:

List of file path

Return type:

list of str

duHast.Utilities.files_get.get_files_from_directory_walker(path, filter)

Gets all files in directory and nested subdirectories where file name contains filter value.

Parameters:
  • path (str) – Folder path from which to get files.

  • filter (str) – File name filter (‘something’)

Returns:

List of file path

Return type:

list of str

duHast.Utilities.files_io module

Helper functions relating to file IO operations.

duHast.Utilities.files_io.file_exist(full_file_path)

Checks whether a file exists :param full_file_path: Fully qualified file path :type full_file_path: str :return: True file exists, otherwise False :rtype: bool

duHast.Utilities.files_io.file_delete(full_file_path)

Deletes file.

Parameters:

full_file_path (str) – Fully qualified file path

Returns:

True if deleted, otherwise False

Return type:

bool

duHast.Utilities.files_io.get_directory_path_from_file_path(file_path)

Extracts directory from file path.

Parameters:

file_path (str) – A fully qualified file path.

Returns:

If no exception occurs : A fully qualified directory path,else an empty string.

Return type:

str

duHast.Utilities.files_io.rename_file(old_name, new_name)

Renames a file. :param old_name: Fully qualified file path to file to be renamed. :type old_name: str :param new_name: Fully qualified new file name. :type new_name: str :return: True file renamed, otherwise False :rtype: bool

duHast.Utilities.files_io.copy_file(old_name, new_name)

Copies a file :param old_name: Fully qualified file path to file to be copied. :type old_name: str :param new_name: Fully qualified path to new file location and name. :type new_name: str :return: True file copied, otherwise False :rtype: bool

duHast.Utilities.files_io.file_move(old_name, new_name)

Moves a file :param old_name: Fully qualified file path to file to be moved. :type old_name: str :param new_name: Fully qualified path to new file location and name. :type new_name: str :return: True file moved, otherwise False :rtype: bool

duHast.Utilities.files_io.FILE_SIZE_IN_KB = 1024

file size in KB conversion

duHast.Utilities.files_io.FILE_SIZE_IN_MB = 1048576

file size in MB conversion

duHast.Utilities.files_io.FILE_SIZE_IN_GB = 1073741824

file size in GB conversion

duHast.Utilities.files_io.get_file_size(file_path, unit=1048576)

Get the file size in given units (default is MB) :param file_path: Fully qualified file path :type file_path: str :param unit: the file size unit, defaults to FILE_SIZE_IN_MB :type unit: int :return: The file size. :rtype: float

duHast.Utilities.files_io.convert_relative_path_to_full_path(relative_file_path, full_file_path)

removes ‘../..’ or ‘../’ from relative file path string and replaces it with full path derived path past in sample path. - relative path sample: ‘C:/temp/../myfile.ext’ - full file path sample: ‘C:/temp/Sample/someOtherFile.ext’ - returns: ‘C:/temp/Sample/myfile.ext’ :param relative_file_path: String containing relative file path annotation. :type relative_file_path: str :param full_file_path: A fully qualified file path of which the relative file path is a sub set. :type full_file_path: str :return: A fully qualified file path. :rtype: str

duHast.Utilities.files_io.get_file_name_without_ext(file_path)

Returns the file name without the file extension.

Parameters:

file_path (str) – Fully qualified file path to file

Returns:

The file name.

Return type:

str

duHast.Utilities.files_io.get_file_extension(file_path)

Returns the file extension of give file name.

Parameters:

file_path (str) – The file name. Can be just the file name or also the fully qualified file path.

Returns:

The file extension in format ‘.extension’

Return type:

str

duHast.Utilities.files_io.read_text_file(file_path)

Reads a text file and returns its content as a single string.

Parameters:

file_path (str) – The fully qualified file path.

Returns:

The content of a text file.

Return type:

str

duHast.Utilities.files_io.read_text_file_into_list(file_path)

Reads a text file and returns its content as a list of string.

It will return

  • one string per row

  • removed line break characters

Parameters:

file_path (str) – The fully qualified file path.

Returns:

The content of a text file. Can be an empty list if an exception occurred during file read.

Return type:

[str]

duHast.Utilities.files_io.get_first_row_in_file(file_path)

Reads the first line of a text file and returns it as a single string with any leading or trailing white spaces stripped!

Parameters:

file_path (str) – The fully qualified file path.

Returns:

The first row of a text file.

Return type:

str

duHast.Utilities.files_io.get_first_row_in_file_no_strip(file_path)

Reads the first line of a text file and returns it as a single string.

Note this may contain a new line character at the end! (”n”)

Parameters:

file_path (str) – The fully qualified file path.

Returns:

The first row of a text file.

Return type:

str

duHast.Utilities.files_io.remove_backup_revit_files_from_list(files)

Takes a list of revit files or full paths and removes any backup files from the list.

Parameters:

files (list) – List of revit files or full paths

Returns:

List of revit files or full paths with backup files removed

Return type:

list

duHast.Utilities.files_io.is_back_up_file(file_path)

Checks whether a file is a Revit back up file.

Backup files are usually in format ‘filename.01234.ext’

Method of checking:

  • splitting file name at every full stop

  • check whether a list with more more then 2 entries came back ?

    • no:
      • not a back up

    • yes:
      • check last list entry whether it is 4 characters in length and can it be convert it into an integer?

        • yes:
          • backup file

        • no
          • normal file

Parameters:

file_path (str) – A fully qualified file path.

Returns:

True if a back up file, otherwise False.

Return type:

bool

duHast.Utilities.files_io.remove_null_bytes(file_path, temp_file_path)

Remove null bytes from a source txt file and write to a temporary file.

Parameters:
  • file_path (str) – The path to the original txt file.

  • temp_file_path (str) – The path to the temporary file where cleaned data is written.

duHast.Utilities.files_io.is_last_char_newline(file_path)

Check if the last character in a file is a newline character.

Parameters:

file_path (str) – The fully qualified file path.

Returns:

True if the last character is a newline, otherwise False.

Return type:

bool

duHast.Utilities.files_json module

Utility functions writing / reading json objects to/ from file.

duHast.Utilities.files_json.serialize(obj)

Serialize the object for JSON output, using to_json() if available.

Parameters:

obj – The object to serialize.

Returns:

A dictionary representation of the object.

duHast.Utilities.files_json.serialize_utf(obj)

Serialize the object for JSON output inluding utf 8, using to_json_utf() if available.

Parameters:

obj – The object to serialize.

Returns:

A dictionary representation of the object.

duHast.Utilities.files_json.write_json_to_file(json_data, data_output_file_path, enforce_utf8=True)

Writes collected data to a new JSON formatted file.

Parameters:
  • json_data – A dictionary to be written to file.

  • data_output_file_path – Fully qualified file path to JSON data file.

  • enforce_utf8 – Will encode any string value as UTF-8, Default is True (recommended!!).

Returns:

Result class instance with status and message.

duHast.Utilities.files_json.read_json_data_from_file(file_path)

Reads json from file

Parameters:

revit_file_path – Fully qualified file path of report file.

Returns:

json object

Return type:

{}

duHast.Utilities.files_tab module

Helper functions relating to tab separated text files.

duHast.Utilities.files_tab.get_unique_headers(files)

Gets a list of alphabetically sorted headers retrieved from text files. Assumes:

  • first row in each file is the header row

  • headers are separated by <tab> character

Parameters:

files (list of str) – List of file path from which the headers are to be returned.

Returns:

List of headers.

Return type:

list of str

duHast.Utilities.files_tab.write_report_data(file_name, header, data, write_type='w', enforce_ascii=False, encoding='utf-8', bom=None, quoting=3)

Function writing out report information.

Parameters:
  • file_name (str) – The reports fully qualified file path.

  • header (list of str) – list of column headers

  • data ([[str,str,..]]) – list of list of strings representing row data

  • write_type (str, optional) – Flag indicating whether existing report file is to be overwritten ‘w’ or appended to ‘a’, defaults to ‘w’

  • enforce_ascci (bool, optional) – Flag to enforce ASCII encoding on data. If True, data will be encoded to ASCII. Defaults to False.

  • encoding (str, optional) – Encoding used to write the file. Defaults to ‘utf-8’.

  • bom (str, default is NoneType) – the byte order mark, Default is None (none will be written). BOM: “utf-16” = , “utf-16-le” = , utf-8 =

  • quoting (int, optional) – Quoting style used by the csv writer. Defaults to csv.QUOTE_NONE. Options are csv.QUOTE_ALL, csv.QUOTE_MINIMAL, csv.QUOTE_NONNUMERIC, csv.QUOTE_NONE

Returns:

A Result object, with the result attribute set to True if the file was written successfully, False otherwise.

Return type:

Result

duHast.Utilities.files_tab.read_tab_separated_file(file_path, increase_max_field_size_limit=False)

Read a tab separated text file into a list of rows, where each row is another list. :param file_path: The fully qualified file path to the tab separated text file. :type file_path: str :return: A list of list of strings representing the data in each row. :rtype: list of list of str

duHast.Utilities.log_decorator module

A decorator factory that returns a decorator that can be used to add logging to a function

duHast.Utilities.log_decorator.get_add_logger_decorator(log_obj_inst, errors_in_console=True, suppress_exceptions=True, record_time=False)

This is a decorator factory that returns a decorator that can be used to add logging to a function. Pass this function an instance of the LoggerObject class from duHast.Utilities.Objects.logger_object.py. Inherit and extend this class to the needs of your application. This will connect the decorator to the logger object application wide. Assign the return value to a variable called log or add_logger etc.

Parameters:
  • log_obj_inst (duHast.Utilities.Objects.logger_object.LoggerObject) – An instance of the LoggerObject class from duHast.Utilities.Objects.logger_object.py

  • errors_in_console (bool) – Whether to output errors to the console. Defaults to True. Turn off to handle in the application code

Returns:

A decorator that can be used to add logging to a function

Return type:

function

duHast.Utilities.logger_filtering module

class duHast.Utilities.logger_filtering.FilterFile(name='')

Bases: Filter

Filter to stop logs to file handler.

To use change your log call to something like: my_logger.info(“This is a console only output”, extra={“block”: “file”})

Initialize a filter.

Initialize with the name of the logger which, together with its children, will have its events allowed through the filter. If no name is specified, allow every event.

filter(record)

Determine if the specified record is to be logged.

Returns True if the record should be logged, or False otherwise. If deemed appropriate, the record may be modified in-place.

class duHast.Utilities.logger_filtering.FilterConsole(name='')

Bases: Filter

Filter to stop logs to console handler.

To use change your log call to something like: my_logger.info(“This is a file only output”, extra={“block”: “console”})

Initialize a filter.

Initialize with the name of the logger which, together with its children, will have its events allowed through the filter. If no name is specified, allow every event.

filter(record)

Determine if the specified record is to be logged.

Returns True if the record should be logged, or False otherwise. If deemed appropriate, the record may be modified in-place.

duHast.Utilities.logger_formatting module

duHast.Utilities.logger_formatting.level_time_utc_msg_formatter()

Standard output formatting for console and file handlers

duHast.Utilities.logger_formatting.level_time_local_msg_formatter()
duHast.Utilities.logger_formatting.msg_only()

Output formatting for presentation

duHast.Utilities.logging_handlers module

class duHast.Utilities.logging_handlers.CustomStreamHandler(custom_function, *args, **kwargs)

Bases: StreamHandler

Initialize the handler.

If stream is not specified, sys.stderr is used.

write(msg)
duHast.Utilities.logging_handlers.std_file_handler(obj, file_hndlr, file_formatter)

Create file handler to obj.log_file_path location

duHast.Utilities.logging_handlers.std_console_handler(obj, cons_hndlr, cons_formatter)

Creates a console handler to output to stdout (console) displaying only the message as default

duHast.Utilities.padding module

This module contains string padding functions for message formatting.

Sample output without a time stamp:

——————————header——————————

or with a time stamp:

23-04-30 20_31_07 : —————–header————————

duHast.Utilities.padding.DEFAULT_PADDING_LENGTH = 90

how long is a padded row

duHast.Utilities.padding.pad_header_no_time_stamp(header_name, padding_length=90)

Pads a header string to be centred in a row of dashes of a given length.

Parameters:
  • header_name (str) – The header

  • padding_length (int, optional) – the length of the padded header excluding time stamp, defaults to 70

Returns:

A padded header row.

Return type:

str

duHast.Utilities.padding.pad_header_with_time_stamp(header_name, padding_length=90)

Pads a header string to be centred in a row of dashes of a given length.

Will also add a time stamp to the beginning of the message.

Parameters:
  • header_name (str) – The header

  • padding_length (int, optional) – the length of the padded header excluding time stamp, defaults to 70

Returns:

A padded header row.

Return type:

str

duHast.Utilities.padding.pad_string(message, padding_length=90)

Pads a string message to be formatted: left hand side message, right hand side status (if any) Maximum length 70 characters (excludes time stamp!) If message is longer then 70-2 characters it will be returned un-changed.

Parameters:
  • message (str) – The message to be padded

  • padding_length (int, optional) – Length of message string after padding, defaults to 70

Returns:

Padded message

Return type:

str

duHast.Utilities.solibri_ifc_optimizer module

Helper functions relating to Solibri IFC optimizer.

List of imports:

duHast.Utilities.solibri_ifc_optimizer.solibri_install_path_ = 'C:\\Program Files\\Solibri\\IFCOptimizer\\Solibri IFC Optimizer.exe'

The default install path for solibri ifc optimizer.

duHast.Utilities.solibri_ifc_optimizer.optimize_all_ifc_files_in_directory(directory_path)

Function applying third party IFC optimizer to all ifc files in a given folder.

Original files will be deleted.

Note: Very large IFC files may fail to optimize. (size larger than approx 1.5GB) Those files will be ignored.

Parameters:

directory_path (str) – The directory path where IFC files are located

Returns:

Result class instance.

  • Optimizer status returned in result.status. False if an exception occurred, otherwise True.

  • result.message will contain the fully qualified file path(s) of the optimized file(s).

On exception (handled by optimizer itself!):

  • result.status (bool) will be False.

  • result.message will contain generic exception message.

Return type:

Result

duHast.Utilities.solibri_ifc_optimizer.optimize_ifc_files_in_list(ifc_files, directory_path)

This function will optimize all IFC files in a given list of fully qualified file path to ifc files.

Will check whether Solibri IFC optimizer is installed.

Parameters:
  • ifc_files (list of str) – List containing fully qualified file path of ifc files to be optimized.

  • directory_path (str) – Directory of where the optimized IFC file(s) are to be saved.

Returns:

Result class instance.

  • Optimizer status returned in result.status. False if an exception occurred, otherwise True.

  • result.message will contain the fully qualified file path(s) of the optimized file(s).

On exception (handled by optimizer itself!):

  • result.status (bool) will be False.

  • result.message will contain generic exception message.

Return type:

Result

duHast.Utilities.solibri_ifc_optimizer.process_ifc_files(ifc_files, directory_path)

This function will optimize all IFC files in a given list of fully qualified file path to ifc files.

Will not check whether Solibri IFC optimizer is installed.

Parameters:
  • ifc_files (list of str) – List containing fully qualified file path of ifc files to be optimized.

  • directory_path (str) – Directory of where the optimized IFC file(s) are to be saved.

Returns:

Result class instance.

  • Optimizer status returned in result.status. False if an exception occurred, otherwise True.

  • result.message will contain the fully qualified file path(s) of the optimized file(s).

On exception (handled by optimizer itself!):

  • result.status (bool) will be False.

  • result.message will contain generic exception message.

Return type:

Result

duHast.Utilities.sub_process module

Start a sub process in a python version of choice.

duHast.Utilities.sub_process.start_sub_process(python_path, script_path)

duHast.Utilities.system_process module

Helper functions relating to system processes.

duHast.Utilities.system_process.get_all_running_processes()

Retrieves a list of all currently running processes.

Returns:

a list in format: [[HandleCount, Name, Priority, ProcessId, ThreadCount, WorkingSetSize]]

Return type:

list of list

duHast.Utilities.system_process.filter_by_process_name(processNames, processList, returnMatch=True)

Filters a provided list of processes by process name

Parameters:
  • processNames (list of str) – List of names to filter by

  • processList ([[HandleCount, Name, Priority, ProcessId, ThreadCount, WorkingSetSize]]) – List of processes running.

  • returnMatch (bool, optional) – If true only matches will be returned, if false any non matches will be returned, defaults to True

Returns:

List of processes

Return type:

[[HandleCount, Name, Priority, ProcessId, ThreadCount, WorkingSetSize]]

duHast.Utilities.system_process.filter_by_process_ids(processIds, processList, returnMatch=True)

Filters a provided list of processes by process ids

Parameters:
  • processIds (_type_) – List of ids to filter by

  • processList ([[HandleCount, Name, Priority, ProcessId, ThreadCount, WorkingSetSize]]) – List of processes running

  • returnMatch (bool, optional) – If true only matches will be returned, if false any non matches will be returned, defaults to True

Returns:

List of processes

Return type:

[[HandleCount, Name, Priority, ProcessId, ThreadCount, WorkingSetSize]]

duHast.Utilities.system_process.kill_processes(processList)

Kills all processes in list provided

Parameters:

processList ([[HandleCount, Name, Priority, ProcessId, ThreadCount, WorkingSetSize]]) – List of processes to be killed.

Returns:

True if all past in processes have been killed, otherwise False.

Return type:

bool

duHast.Utilities.system_process.write_out_process_data(directoryPath, processList, fileName, fileExtension)

Writes out process data to file

Parameters:
  • directoryPath (str) – The directory path to where the export is being saved.

  • processList ([[HandleCount, Name, Priority, ProcessId, ThreadCount, WorkingSetSize]]) – List of processes to be written to file.

  • fileName (str) – The file name under which the export is being saved (excluding file extension).

  • fileExtension (str) – in format ‘.extension’

Returns:

True if the process data was written to file without an exception, otherwise False.

Return type:

bool

duHast.Utilities.unit_conversion module

This module contains a number of unit conversion functions

duHast.Utilities.unit_conversion.convert_imperial_feet_to_metric_mm(value)

Converts feet and inches to mm :param value: The value in feet to be converted :type value: float :return: The converted value :rtype: float

duHast.Utilities.unit_conversion.convert_imperial_square_feet_to_metric_square_metre(value)

Converts square feet and inches to square m

Parameters:

value (float) – The value in square feet to be converted

Returns:

The converted value

Return type:

float

duHast.Utilities.unit_conversion.convert_imperial_cubic_feet_to_metric_cubic_metre(value)

Converts cubic feet and inches to cubic m

Parameters:

value (float) – The value in cubic feet to be converted

Returns:

The converted value

Return type:

float

duHast.Utilities.unit_conversion.convert_mm_to_imperial_feet(length)

Convert a length value in millimeters to imperial feet.

Parameters:

length (float) – A float value representing the length in millimeters.

Returns:

A float value representing the length in imperial feet.

duHast.Utilities.util_batch_p module

This module contains a number of helper functions relating to batch processor.

duHast.Utilities.util_batch_p.adjust_session_id_for_file_name(id)

Removes chevrons and replace colons with underscores in session id supplied by revit batch processor so it can be used in a file name.

Parameters:

id (str) – Session id supplied by revit batch processor.

Returns:

Re-formatted session id.

Return type:

str

duHast.Utilities.util_batch_p.adjust_session_id_file_name_back(file_name_id)

Re-introduces chevrons and replaces underscores with colons to match session Id format used in batch processor to a file name using a batch processor supplied id.

Parameters:

file_name_id (str) – A file name containing a session id with all illegal characters replaced.

Returns:

A session id.

Return type:

str

duHast.Utilities.util_batch_p.adjust_session_id_for_directory_name(id)

Removes chevrons and replace colons, full stops, dashes with underscores in session id supplied by revit batch processor so it can be used in a folder name.

Parameters:

id (str) – Session id supplied by revit batch processor.

Returns:

Re-formatted session id.

Return type:

str

duHast.Utilities.utility module

This module contains a number of helper functions

duHast.Utilities.utility.get_local_app_data_path()

return directory path to local app data folder

Returns:

Path to local app data

Return type:

str

duHast.Utilities.utility.get_current_user_name()

Returns the current user name

Returns:

the user name

Return type:

str

duHast.Utilities.utility.parse_string_to_bool(text)

Converts a string to lower case and then to bool. Will throw an exception if it fails to do so.

( ‘true’ = True, ‘false’ = False)

Parameters:

text (str) – The string representing a bool.

Raises:

Exception – If string to bool conversion fails the ‘String cant be converted to bool’ exception will be raised.

Returns:

True or False

Return type:

bool

duHast.Utilities.utility.PAD_SINGLE_DIGIT_TO_TWO = '%02d'

two digit padding

duHast.Utilities.utility.PAD_SINGLE_DIGIT_TO_THREE = '%03d'

three digit padding

duHast.Utilities.utility.pad_single_digit_numeric_string(numericString, format='%02d')

Pads a single digit integer (past in as a string) with a leading zero (default)

Parameters:
  • numericString (str) – Integer as string.

  • format (str, optional) – The integer padding format, defaults to PAD_SINGLE_DIGIT_TO_TWO

Returns:

The padded integer as string.

Return type:

str

duHast.Utilities.utility.encode_ascii(string)

Encode a string as ascii and replaces all non ascii characters

If a non string is past in the value will be returned unchanged.

Parameters:

string (str) – The string to be ascii encoded.

Returns:

ascii encoded string

Return type:

str

duHast.Utilities.utility.encode_utf8(string)

Encode a string as utf-8 and replaces all non utf-8 characters

If a non string is past in the value will be returned unchanged.

Parameters:

string (str) – The string to be utf-8 encoded.

Returns:

utf-8 encoded string

Return type:

str

duHast.Utilities.utility.get_first(iterable, default, condition=<function <lambda>>)

Returns the first value in a list matching condition. If no value found returns the specified default value.

Parameters:
  • iterable (iterable) – the list to be searched.

  • default (var) – The default value

  • condition (_type_, optional) – The condition to be checked, defaults to lambda x:True

Returns:

First value matching condition, otherwise default value

Return type:

var

duHast.Utilities.utility.index_of(list, item)

Gets the index of item in list

Parameters:
  • list (list) – The list

  • item (var) – The item of which to return the index.

Returns:

The index of the item in the list, if no match -1 will be returned

Return type:

int

duHast.Utilities.utility.remove_items_from_list(sourceList, removeIdsList)

helper removes items from a source list

Parameters:
  • sourceList (list var) – The list containing items

  • removeIdsList (list var) – the list containing items to be removed

Returns:

The filtered source list.

Return type:

list var

duHast.Utilities.utility.flatten(d, parent_key='', sep='_')

Flattens a dictionary as per stack overflow

https://stackoverflow.com/questions/6027558/flatten-nested-dictionaries-compressing-keys/6027615#6027615

Parameters:
  • d (_type_) – _description_

  • parent_key (str, optional) – _description_, defaults to ‘’

  • sep (str, optional) – _description_, defaults to ‘_’

Returns:

_description_

Return type:

_type_

duHast.Utilities.utility.flatten_list(lst)

Function to flatten a nested list

Parameters:

lst (list) – The list to be flattened

Returns:

The flattened list

Return type:

list

duHast.Utilities.worksharing_monitor_process module

Helper functions relating to Revit worksharing monitor process.

duHast.Utilities.worksharing_monitor_process.get_work_sharing_monitor_processes()

Get all currently running worksharing monitor processes

Returns:

_description_

Return type:

[[HandleCount, Name, Priority, ProcessId, ThreadCount, WorkingSetSize]]

duHast.Utilities.worksharing_monitor_process.write_out_wsm_data_to_file(directory_path)

Writes out all running worksharing monitor processes data to file

Parameters:

directory_path (str) – The directory path to where the marker file is to be saved.

Returns:

Result class instance.

  • Export status returned in result.status. False if an exception occurred, otherwise True.

  • result.message will contain the fully qualified file path of the exported file.

On exception:

  • result.status (bool) will be False.

  • result.message will contain the exception message.

Return type:

Result

duHast.Utilities.worksharing_monitor_process.delete_wsm_data_files(directory_path)

Deletes all WSM marker files in a directory.

WSM marker files got a specific file extension: Check: PROCESS_MARKER_FILE_EXTENSION

Parameters:

directory_path (str) – The directory path containing marker files to be deleted.

Returns:

True if all files where deleted successfully, otherwise False.

Return type:

bool

duHast.Utilities.worksharing_monitor_process.read_wsm_data_from_file(directory_path)

Reads all worksharing monitor processes data from marker file(s) in a given directory

WSM marker files got a specific file extension: Check: PROCESS_MARKER_FILE_EXTENSION

Parameters:

directory_path (str) – The directory path to where marker files are to be read from.

Returns:

list of list of str

Return type:

[[HandleCount, Name, Priority, ProcessId, ThreadCount, WorkingSetSize]]

duHast.Utilities.worksharing_monitor_process.get_wsm_sessions_to_delete(ws_ms_to_keep)

Returns Worksharing monitor process sessions filtered by provided list (not in list)

Parameters:

ws_ms_to_keep (List of list of str in format: [[HandleCount, Name, Priority, ProcessId, ThreadCount, WorkingSetSize]]) – List of worksharing monitor sessions to filter by. WSM included in this list will be removed from past in list.

Returns:

Filtered list of list of str of worksharing monitor sessions

Return type:

[[HandleCount, Name, Priority, ProcessId, ThreadCount, WorkingSetSize]]

duHast.Utilities.worksharing_monitor_process.clean_up_wsm_data_files(directory_path)

Removes all wsm data marker files in a given directory.

WSM marker files got a specific file extension: Check: PROCESS_MARKER_FILE_EXTENSION.

Parameters:

directory_path (str) – The directory path containing the marker files to be deleted.

Returns:

Result class instance.

  • Delete status returned in result.status. False if an exception occurred, otherwise True.

  • result.message will confirm successful deletion of all files.

On exception:

  • result.status (bool) will be False.

  • result.message will contain the exception message.

Return type:

Result

duHast.Utilities.worksharing_monitor_process.die_wsm_die(directory_path, ignore_marker_files=False)

Kills all worksharing monitor processes currently active.

Unless marker files are used. In that case only worksharing monitor sessions identified in marker files will be killed.

Parameters:
  • directory_path (str) – The directory path to where marker files are to be read from.

  • ignore_marker_files (bool, optional) – True no marker file data will be read and all WSM sessions running will be killed., defaults to False

Returns:

Result class instance.

  • Kill status returned in result.status. False if an exception occurred, otherwise True.

  • result.message will confirm successful killing of all WSM processes.

On exception:

  • result.status (bool) will be False.

  • result.message will contain the exception message.

Return type:

Result

Module contents