如何使用Python子进程启动Windows命令提示符?
我花了好几个小时在这上面绞尽脑汁,还在网上找了很多答案,但都没有找到合适的。我想让我的程序能检测是否安装了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'和Windows命令提示符尝试启动pip安装时出错。非常期待你们的建议!
更新:我想起来我忘了贴我的系统配置了。我现在使用的是Eclipse 4.4(Luna)和PyDev插件(3.6.0.201406232321)。我的操作系统是Windows 8.1专业版64位,安装了Python 2.7和Python 3.4。目前默认的Python版本是2.7。
1 个回答
1
在编程中,有时候我们会遇到一些问题,可能是因为代码写得不够好,或者是我们对某些概念理解得不够透彻。比如,有人可能在使用某个库的时候,遇到了错误,或者是代码没有按照预期的方式运行。这种情况下,查看别人遇到的类似问题和解决方案就显得很重要。
在StackOverflow上,很多开发者会分享他们的经验和解决方法。你可以在这里找到各种各样的问题和答案,帮助你更好地理解编程中的各种情况。
记住,遇到问题是很正常的,关键是要学会如何寻找解决方案,并从中吸取经验教训。
#!/usr/bin/env python
from subprocess import check_output
print check_output("dir c:;pwd;", shell=True)