【问题标题】:Access Tools from .venv从 .venv 访问工具
【发布时间】:2022-11-29 07:50:29
【问题描述】:

从脚本中访问 python 工具的最佳方式是什么?

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

在 Linux 系统上可能没有问题,因为它们已经在 PATH 上,但在 Windows 下我必须用 python 作为解释器来调用它们,因此在路径上设置目录不像在 Linux 中那样工作。

那么调用os.system('my_pygettext_command')实际上是正确的尝试还是我应该用不同的方法来做到这一点,比如导入?如果导入是正确的,如果它们只安装在系统安装中而不是在venv中,我该如何访问它们

【问题讨论】:

    标签: python gettext


    【解决方案1】:

    进一步研究这个话题,我真的被吞噬了:

    也许我在 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("
    ") 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"
    

    【讨论】:

      猜你喜欢
      • 2017-01-26
      • 2020-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多