[英]Access Tools from .venv
What is the best way to access python tools from within a script?从脚本中访问 python 工具的最佳方式是什么?
For my example I want to use msgfmt.py
and pygettext
from the Tools/i18n
package(?).对于我的示例,我想使用
Tools/i18n
包(?)中的msgfmt.py
和pygettext
。
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.在 Linux 系统上可能没有问题,因为它们已经在
PATH
上,但在 Windows 下我必须用python
作为解释器调用它们,因此在路径上设置目录不像在 Linux 中那样工作。
So is calling os.system('my_pygettext_command')
actually the right attempt or should I do this with a different approach, like importing?那么调用
os.system('my_pygettext_command')
实际上是正确的尝试还是我应该用不同的方法来做到这一点,比如导入? If importing would be correct, how can I access them, if they are only installed on the system installation and not in venv
如果导入是正确的,如果它们只安装在系统安装中而不是在
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.也许我在 windows 下做的完全错了,但我的线路比率(linux/windows)从 venv 内部调用 python 工具:1/34。 I did not fully tested the final call under linux yet, but this ratio is only for getting the
subprocess
command. linux下的最终调用我还没有完全测试,这个比例只是为了获取
subprocess
命令。
This is my momentary solution and I am open for better approaches:这是我的临时解决方案,我愿意接受更好的方法:
windows-utils Windows实用程序
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"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.