Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding new argument to generate_dynamic: tmp_dir_path and tmp_file_name #125

Open
wants to merge 4 commits into
base: kinetic-devel
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 16 additions & 9 deletions src/genpy/dynamic.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,13 +111,14 @@ def _gen_dyn_modify_references(py_text, current_type, types):
return py_text


def generate_dynamic(core_type, msg_cat):
def generate_dynamic(core_type, msg_cat, output_file=None):
"""
Dymamically generate message classes from msg_cat .msg text gendeps dump.

This method modifies sys.path to include a temp file directory.
:param core_type str: top-level ROS message type of concatenated .msg text
:param msg_cat str: concatenation of full message text (output of gendeps --cat)
:param output_file str: user-specified path of output file
:raises: MsgGenerationException If dep_msg is improperly formatted
"""
msg_context = MsgContext.create_default()
Expand Down Expand Up @@ -161,16 +162,22 @@ def generate_dynamic(core_type, msg_cat):
buff.write(line + '\n')
full_text = buff.getvalue()

# Create a temporary directory
tmp_dir = tempfile.mkdtemp(prefix='genpy_')
if output_file:
# create file with specified temp file name, overwrite file if already exist
tmp_file = open(output_file, 'w')
else:
# Create a temporary directory
tmp_dir = tempfile.mkdtemp(prefix='genpy_')

# Afterwards, we are going to remove the directory so that the .pyc file gets cleaned up if it's still around
atexit.register(shutil.rmtree, tmp_dir)
# Afterwards, we are going to remove the directory so that the .pyc file gets cleaned up if it's still around
atexit.register(shutil.rmtree, tmp_dir)

# write the entire text to a file and import it (it will get deleted when tmp_dir goes - above)
tmp_file = tempfile.NamedTemporaryFile(mode='w', suffix='.py', dir=tmp_dir, delete=False)
tmp_file.file.write(full_text)
tmp_file.file.close()
# write the entire text to a file and import it (it will get deleted when tmp_dir goes - above)
tmp_file = tempfile.NamedTemporaryFile(mode='w', suffix='.py', dir=tmp_dir, delete=False)

# write the entire text to a file and import it
tmp_file.write(full_text)
tmp_file.close()

# import our temporary file as a python module, which requires modifying sys.path
sys.path.append(os.path.dirname(tmp_file.name))
Expand Down