如何使用Python子进程启动Windows命令提示符?

时间:2014-07-08 06:46:50

标签: python windows subprocess pip mysql-connector-python

我一直在敲打这个问题好几个小时,并在互联网上寻找答案。我怕我干了。我的程序的这一部分将检测是否安装了Python的MySQL Connector模块,如果没有,将使用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,但是我很难尝试使用' subprocess'启动pip安装。和Windows命令提示符。非常兴奋您的意见!

更新:提醒我忘记发布系统规格。我正在使用PyDev插件(3.6.0.201406232321)运行Eclipse 4.4(Luna)。我的操作系统是Windows 8.1 Professional 64位,我安装了Python 2.7和Python 3.4。我的默认Python版本目前是2.7。

1 个答案:

答案 0 :(得分:1)

#!/usr/bin/env python
from subprocess import check_output
print check_output("dir c:;pwd;", shell=True)