我已经为此苦苦思索了好几个小时,并在互联网上寻找答案。我怕我干了。我的程序的这一部分将检测是否安装了 Python 的 MySQL 连接器模块,如果没有,将使用 PIP 安装它。这里有适用于 Windows 和另一个的代码。我试图让 Windows 部分工作,但对于我的生活,似乎无法做到。这是代码块(请原谅任何废话,我一直在黑暗中刺伤):
try:
import mysql.connector as MySQL
except ImportError:
print("In order to use this program, you need a MySQL connector module,")
print("provided by MySQL. Do you wish to install this module (uses SUDO)? (y/n)")
ans = input()
if ans == "y":
import subprocess
if os.name == 'nt': # Windows users will have a different call
try:
subprocess.call("pip install mysql-connector-python", shell = True)
except:
print("Unable to install module...exiting")
exit(1)
raise SystemExit
else:
try:
subprocess.call("sudo pip3 install --allow-external mysql-connector-python mysql-connector-python", shell = True)
except:
print("Unable to install module...exiting")
exit(1)
raise SystemExit
print("The MySQL Connector module was unable to be installed...exiting.")
exit(1)
raise SystemExit
else:
print("The module mysql-connector-python needs to be installed to use this program.")
print("Module was not installed. Exiting...")
raise SystemExit
运行程序后,这是我在控制台中得到的输出:
Please choose either the 'O' or 'D' option. Print 'H' or 'HELP' for help. Print 'Q' to quit.
--> d
In order to use this program, you need a MySQL connector module,
provided by MySQL. Do you wish to install this module (uses SUDO)? (y/n)
y
Fatal Python error: Py_Initialize: unable to load the file system codec
File "C:\Python27\lib\encodings\__init__.py", line 123
raise CodecRegistryError,\
^
SyntaxError: invalid syntax
The MySQL Connector module was unable to be installed...exiting.
我很确定问题不在于 CodecRegistryError,而在于我尝试使用“子进程”和 Windows 命令提示符启动 pip 安装时表现不佳。对您的意见感到非常兴奋!
更新:提醒我忘记发布我的系统规格。我正在使用 PyDev 插件 (3.6.0.201406232321) 运行 Eclipse 4.4 (Luna)。我的操作系统是 Windows 8.1 Professional 64 位,我安装了 Python 2.7 和 Python 3.4。我的默认 Python 版本目前是 2.7。