簡體   English   中英

從 .venv 訪問工具

[英]Access Tools from .venv

從腳本中訪問 python 工具的最佳方式是什么?

對於我的示例,我想使用Tools/i18n包(?)中的msgfmt.pypygettext

在 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM