What is the best way to access python tools from within a script?
For my example I want to use msgfmt.py
and pygettext
from the Tools/i18n
package(?).
On a Linux system probably no issue, since they are already on the PATH
, but under Windows I have to call them with python
as interpreter, so setting the directory on the path doesn't work like in Linux.
So is calling os.system('my_pygettext_command')
actually the right attempt or should I do this with a different approach, like importing? If importing would be correct, how can I access them, if they are only installed on the system installation and not in venv
Researching a bit further into the topic, I got really mind gobbled:
Maybe I am doing this totally wrong under windows, but my line ratio (linux/windows) to call a python tool from inside a venv: 1/34. I did not fully tested the final call under linux yet, but this ratio is only for getting the subprocess
command.
This is my momentary solution and I am open for better approaches:
windows-utils
import sys
from typing import Dict
def stdout_get_command_to_dict(string: str):
lines = [s for s in string.split("\n") if s]
# remove header
lines = lines[2:]
stdout_dict = {}
for idx, line in enumerate(lines):
# Reduce Spaces
while " " in line:
line = line.replace(" ", " ")
line_as_list = line.split()
stdout_dict[idx] = {
"Version": line_as_list[2][:5],
"Source": line_as_list[3],
"Venv": line_as_list[3].find("venv") > 0,
}
return stdout_dict
def get_system_py_path(stdout_dict: Dict[int, Dict[str, str]]):
major = sys.version_info.major
minor = sys.version_info.minor
micro = sys.version_info.micro
env_version = f"{major}.{minor}.{micro}"
for key in stdout_dict.keys():
if stdout_dict[key]["Version"] == env_version and not stdout_dict[key]["Venv"]:
return stdout_dict[key]["Source"]
and the script:
if platform.system() == "Windows":
cmd = ["powershell", "get-command", "python", "-totalCount", "4"]
processed_cmd = subprocess.run(cmd, shell=True, capture_output=True, text=True)
stdout_as_dict = stdout_get_command_to_dict(processed_cmd.stdout)
sys_python_path = Path(get_system_py_path(stdout_as_dict)).parent
tool = sys_python_path / "Tools/i18n/msgfmt.py"
tool_cmd = f"python {tool}"
elif platform.system() == "Linux":
tool_cmd = "msgfmt"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.