def run_script_str(script_str):
    """Execute a Python string through the shell in a temporary directory.

    With respect to eval, this has the advantage of catching all import errors.

    """
    with temporary_directory() as tmp_dir:
        temp_file_path = os.path.join(tmp_dir, 'temp.py')
        # Create temporary python script.
        with open(temp_file_path, 'w') as f:
            f.write(script_str)
        # Run the Python script.
        try:
            run_script_file(temp_file_path)
        except:
            script_str = textwrap.indent(script_str, '    ')
            raise Exception(f'The following script failed:\n{script_str}')
Beispiel #2
0
def test_temporary_directory():
    """Test temporary_directory() context manager"""
    from openforcefield.utils import temporary_directory
    initial_dir = os.getcwd()
    with temporary_directory() as tmp_dir:
        # Make sure the temporary directory is not the current directory
        assert tmp_dir != initial_dir

        # Make sure the temporary directory is writeable
        output_filename = os.path.join(tmp_dir, 'test.out')
        outfile = open(output_filename, 'w')
        outfile.write('test')
        outfile.close()

        # Make sure the file we created exists
        assert os.path.exists(output_filename)

    # Make sure the directory has been cleaned up
    assert not os.path.exists(
        tmp_dir), "Temporary directory was not automatically cleaned up."
    assert not os.path.exists(
        output_filename
    ), "Temporary directory was not automatically cleaned up."