![](/img/trans.png)
[英]From a Python venv, find installation from which the venv command was run
[英]Access Tools from .venv
从脚本中访问 python 工具的最佳方式是什么?
对于我的示例,我想使用Tools/i18n
包(?)中的msgfmt.py
和pygettext
。
在 Linux 系统上可能没有问题,因为它们已经在PATH
上,但在 Windows 下我必须用python
作为解释器调用它们,因此在路径上设置目录不像在 Linux 中那样工作。
那么调用os.system('my_pygettext_command')
实际上是正确的尝试还是我应该用不同的方法来做到这一点,比如导入? 如果导入是正确的,如果它们只安装在系统安装中而不是在venv
中,我该如何访问它们
进一步研究这个话题,我真的被吞噬了:
也许我在 windows 下做的完全错了,但我的线路比率(linux/windows)从 venv 内部调用 python 工具:1/34。 linux下的最终调用我还没有完全测试,这个比例只是为了获取subprocess
命令。
这是我的临时解决方案,我愿意接受更好的方法:
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"]
和脚本:
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.