diff --git a/src/scribe_data/wikidata/query_data.py b/src/scribe_data/wikidata/query_data.py index afd12e41..3ec6657a 100644 --- a/src/scribe_data/wikidata/query_data.py +++ b/src/scribe_data/wikidata/query_data.py @@ -22,6 +22,8 @@ import json import os +import subprocess +import sys from pathlib import Path from urllib.error import HTTPError @@ -33,6 +35,52 @@ from scribe_data.wikidata.wikidata_utils import sparql +def execute_formatting_script(formatting_file_path, output_dir): + """ + Executes a formatting script given a filepath and output directory for the process. + + Parameters + ---------- + formatting_file_path : str + The formatting file to run. + + output_dir : str + The output directory path for results. + + Returns + ------- + The results of the formatting script saved in the given output directory. + """ + # Determine the root directory of the project. + project_root = Path(__file__).parent.parent + + if sys.platform.startswith("win"): + python_executable = sys.executable + pythonpath = str(project_root) + + # Create environment with updated PYTHONPATH. + env = os.environ.copy() + if "PYTHONPATH" in env: + env["PYTHONPATH"] = f"{pythonpath};{env['PYTHONPATH']}" + + else: + env["PYTHONPATH"] = pythonpath + + # Use subprocess.run instead of os.system. + subprocess.run( + [python_executable, str(formatting_file_path), "--file-path", output_dir], + env=env, + check=True, + ) + + else: + # Unix-like systems (Linux, macOS). + subprocess.run( + ["python3", str(formatting_file_path), "--file-path", output_dir], + check=True, + ) + + def query_data( languages: str = None, data_type: str = None, @@ -262,7 +310,9 @@ def query_data( / target_type / f"format_{target_type}.py" ) - os.system(f"python3 {formatting_file_path} --file-path {output_dir}") + execute_formatting_script( + formatting_file_path=formatting_file_path, output_dir=output_dir + ) if __name__ == "__main__":