我试图遵循这里的建议:https://stackoverflow.com/a/58040520/3403085
但我仍然收到错误。请参阅下面的代码:
import subprocess
import sys
try:
import pandas
except ImportError:
subprocess.call([sys.executable, "-m", "pip", "install", 'pandas'])
finally:
import pandas
print(pandas.__version__)
这是我运行命令时的输出:
Collecting pandas
Downloading https://files.pythonhosted.org/packages/63/e0/a1b39cdcb2c391f087a1538bc8a6d62a82d0439693192aef541d7b123769/pandas-0.25.3-cp37-cp37m-manylinux1_x86_64.whl (10.4MB)
100% |████████████████████████████████| 10.4MB 13.8MB/s
Collecting python-dateutil>=2.6.1 (from pandas)
Downloading https://files.pythonhosted.org/packages/d4/70/d60450c3dd48ef87586924207ae8907090de0b306af2bce5d134d78615cb/python_dateutil-2.8.1-py2.py3-none-any.whl (227kB)
100% |████████████████████████████████| 235kB 13.9MB/s
Collecting pytz>=2017.2 (from pandas)
Downloading https://files.pythonhosted.org/packages/e7/f9/f0b53f88060247251bf481fa6ea62cd0d25bf1b11a87888e53ce5b7c8ad2/pytz-2019.3-py2.py3-none-any.whl (509kB)
100% |████████████████████████████████| 512kB 11.7MB/s
Collecting numpy>=1.13.3 (from pandas)
Downloading https://files.pythonhosted.org/packages/9b/af/4fc72f9d38e43b092e91e5b8cb9956d25b2e3ff8c75aed95df5569e4734e/numpy-1.17.4-cp37-cp37m-manylinux1_x86_64.whl (20.0MB)
100% |████████████████████████████████| 20.0MB 14.1MB/s
Collecting six>=1.5 (from python-dateutil>=2.6.1->pandas)
Downloading https://files.pythonhosted.org/packages/65/26/32b8464df2a97e6dd1b656ed26b2c194606c16fe163c695a992b36c11cdf/six-1.13.0-py2.py3-none-any.whl
Installing collected packages: six, python-dateutil, pytz, numpy, pandas
Successfully installed numpy-1.17.4 pandas-0.25.3 python-dateutil-2.8.1 pytz-2019.3 six-1.13.0
Traceback (most recent call last):
File "test.py", line 9, in <module>
import pandas
ModuleNotFoundError: No module named 'pandas'
如果我再次运行脚本,pandas
模块将成功导入,而无需重新安装,并且我得到以下输出:
0.25.3
我也可以通过运行python3 -m pip uninstall pandas
卸载,这样我就可以确认它确实已安装。任何想法为什么如果尚未安装熊猫会失败?
解决方案在该线程中的另一个答案中:https://stackoverflow.com/a/24773951/6417038
finally:
globals()[package] = importlib.import_module(package)