我是一个完全 Python 初学者,我尝试编写一个Python 脚本 以从远程Linux 机器上自动设置SDK < em>Github 存储库。
该脚本首先执行一些基本的预备操作,尤其是几个包的检查/设置(git
、docker
、 pip
等)。
目前,我的目标是 Debian(Stretch、Buster)、Centos(6、7)和 Ubuntu Server 18.04LTS。 当然,我希望脚本能够在最广泛的 linux 机器上运行。
今天我依赖可用的包管理器(apt-get
和yum
),大致通过subprocess.call() 请求
语句。
我使用 讨厌的 脚本配置变量自定义相关命令,如下所示:
import platform
distribution = platform.dist()[0]
version = platform.dist()[1]
if distribution == 'debian':
pkgInstaller = 'dpkg'
pkmManager = 'apt-get'
checkIfInstalled = '-s'
installPackage = 'install'
yesToAll = '-y'
dockerPackage = 'docker-ce'
elif distribution == 'centos':
pkgInstaller = 'rpm'
pkgManager = 'yum'
checkIfInstalled = '-q'
installPackage = 'install'
yesToAll = '-y'
dockerPackage = 'docker'
然后我简单地在包含要安装的包的名称 的数组 上循环,然后通过subprocess.call()
运行命令:
prerequisites = ['git', dockerPackage, 'doxygen', 'python2-pip']
for pkg in prerequisites:
pgkInstallation = subprocess.call(['sudo', pkgManager, yesToAll, installPackage, pkg])
虽然这种方法的好处是不会太多绑定(bind)到第三方 Python 模块,我想有...一些更聪明的方法做这么简单的操作?
最佳答案
通常在执行这样的 switch 语句时,字典可能会更有用。另外,通常我不是一个尝试 PEP-8 的人,但在这个例子中,PEP-8 可能会通过不匹配所有代码行的等号来真正帮助您提高可读性。
dict
将把你的 distro
作为键,把你的变量作为一个值包裹在一个元组中
options = {
'debian': ('dpkg', 'apt-get', '-s', 'install', '-y', 'docker-ce'),
'centos': ('rpm', 'yum', '-q', 'install', '-y', 'docker'),
}
# unpack this function call here
distribution, version, *_ = platform.dist()
# now get the match
pkg_installer, pkg_manager, check, install_pkg, yes_to_all, docker = options[distribution]
requisites = ['git', docker, 'doxygen', 'python2-pip']
for pkg in requisites:
pgkInstallation = subprocess.call(['sudo', pkg_manager, yes_to_all, install_pkg, pkg])
options[distribution]
调用将为不受支持的分发引发 KeyError
,因此您可能会捕捉到它并引发一些更有用的东西,例如:
try:
pkg_installer, pkg_manager, check, install_pkg, yes_to_all, docker = options[distribution]
except KeyError as e:
raise ValueError(f"Got unsupported OS, expected one of {', '.join(options.keys())}") from e
为了让它不那么冗长,唯一乱序使用的变量是 docker
,因此您可以将所有其他变量放在一个变量中:
try:
*args, docker = options[distribution]
except KeyError as e:
raise ValueError(f"Got unsupported OS, expected one of {', '.join(options.keys())}") from e
requisites = ['git', docker, 'doxygen', 'python2-pip']
for pkg in requisites:
pgkInstallation = subprocess.call(['sudo', *args, pkg])
关于python - 使用 Python 进行 Linux 包管理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57610644/