Coverage for skema/program_analysis/python_preprocessor.py: 100%

16 statements  

« prev     ^ index     » next       coverage.py v7.5.0, created at 2024-04-30 17:15 +0000

1import subprocess 

2import tempfile 

3from pathlib import Path 

4 

5def preprocess(source: str): 

6 return convert_python2_to_python3(source) 

7 

8def convert_python2_to_python3(source: str): 

9 # Create a temporary file to hold the Python 2 code 

10 with tempfile.NamedTemporaryFile(delete=False, mode='w', suffix='.py') as temp_file: 

11 temp_file_path = Path(temp_file.name) 

12 temp_file.write(source) 

13 

14 # Run 2to3 on the temporary file 

15 try: 

16 subprocess.run(['2to3', '--write', '--nobackups', str(temp_file_path)], check=True) 

17 preprocessed_code = temp_file_path.read_text() 

18 except subprocess.CalledProcessError: 

19 preprocessed_code = source 

20 

21 # Clean up the temporary file 

22 temp_file_path.unlink() 

23 

24 return preprocessed_code