我已經在這個問題上打了很多個小時,並且已經在互聯網上尋找答案。恐怕我幹起來了。我的程序的這一部分將檢測是否安裝了Python的MySQL連接器模塊,如果沒有,將使用PIP來安裝它。這裏有兩個Windows和另一個代碼。我試圖讓Windows部分工作,但對於我的生活,似乎無法做到這一點。下面是代碼塊(原諒任何廢話,我在黑暗中刺):如何使用Python子進程啓動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,而是我嘗試使用'subprocess'和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。
這個答案適合您嗎? [使用python運行windows shell命令](http://stackoverflow.com/questions/14894993/running-windows-shell-commands-with-python) –
對不起,但它沒有幫助。我相信這個問題可能與我的具體計算環境有關。我將在另一個系統上嘗試它,看看它是否可以解決問題。我會回報。 –
在其他Windows電腦上嘗試過,無濟於事。我在Linux環境中設置了程序,它工作得很好。它也可以在Mac環境中使用。感謝您的幫助,雖然...驚訝沒有人插話! : -/ –