我想编写一个具有良好异常处理功能的函数,以确保在工作环境中安装了所有必要的包。我需要导入两个或更多包并使代码可重用,我想循环从字典中导入的包。
这是我没有循环的代码:
def pkgs_install():
import subprocess
import sys
try:
import pandas as pd
print('{} is already installed'.format('Pandas'))
except ImportError:
print('{} is not installed and has to be installed'.format('Pandas'))
subprocess.call([sys.executable, '-m', 'pip', 'install', 'pandas'])
finally:
import pandas as pd
print('{} is properly installed'.format('Pandas'))
try:
import numpy
print('{} is already installed'.format('Numpy'))
except ImportError:
print('{} is not installed and has to be installed'.format('Numpy'))
subprocess.call([sys.executable, '-m', 'pip', 'install', 'numpy'])
finally:
import numpy
print('{} is properly installed'.format('Numpy'))
print("All packages have been imported. You're good to go!")
这段代码可以正常工作,但现在创建循环要困难得多。我尝试了一段代码,但现在卡住了。这是我的代码:
def pkgs_install():
import subprocess
import sys
pkgs = {'pandas': 'pd', 'numpy': 'np'}
for p in pkgs:
s = pkgs[p]
try:
import p as s
print('{} is already installed'.format(p))
except ImportError:
print('{} is not installed and has to be installed'.format(p))
subprocess.call([sys.executable, '-m', 'pip', 'install', p])
finally:
import p as s
print('{} is properly installed'.format(p))
print("All packages have been imported. You're good to go!")
有人知道如何解决这个问题吗?
非常感谢!