Python CLI“-c”与Popen语法无效

问题描述 投票:1回答:1

我有一个程序,我需要检查一台机器是否具有所需的所有Python模块依赖项。该机器可以是本地机器或远程机器。因此,为了概括代码,我正在执行系统命令(因此脚本可以从任何地方运行,连接到机器并运行命令)

如果python脚本在本地检查,则它正在运行以下命令

cmd = "python -c \"import myRequiredModule\""
pg = Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True, executable="/path/to/powershell")

但输出如下:

  File "<string>", line 1
    import
         ^
SyntaxError: invalid syntax

如果我只是打开PowerShell并运行它,它似乎工作正常。为什么这会失败?

python powershell subprocess popen
1个回答
0
投票

你有几个选择:

您可以使用需求文件并告诉PIP安装缺少的内容:

python -m pip install -r requirements.txt

你可以编写一个Python程序来打印出丢失的模块:

from pkgutil import iter_modules
modules = set(x[1] for x in iter_modules())

with open('requirements.txt', 'rb') as f:
    for line in f:
        requirement = line.rstrip()
        if not requirement in modules:
            print requirement

或者您可以编写一个Python程序,它将尝试自行安装缺少的模块:

import pip

def import_or_install(package_name):
    try:
        __import__(package_name)
    except ImportError:
        pip.main(['install', package_name])
© www.soinside.com 2019 - 2024. All rights reserved.