简体   繁体   English

Windows命令提示不适用于Python

[英]Windows Command Prompt Not working From Python

I am trying to get the following command (which works when entered manually to shut down mysql server) working from python. 我正在尝试从python获取以下命令(在手动输入以关闭mysql服务器时有效)。

The line of code I am running is: 我正在运行的代码行是:

os.system('"C:\Program Files\MySQL\MySQL Server 5.1\bin\mysqladmin" -u demo -pdemopw shutdown')

Any ideas why this would work from the command prompt, but not from os.system, and how I can fix it? 有什么想法为什么可以从命令提示符下而不是os.system上运行?如何解决?

When working with Windows file\\folder paths, I almost always use raw strings. 使用Windows文件\\文件夹路径时,几乎总是使用原始字符串。 Here is an example: 这是一个例子:

sql_admin = r"C:\Program Files\MySQL\MySQL Server 5.1\bin\mysqladmin"

Notice the r at the beginning of the string. 注意字符串开头的r That turns the string into a raw string. 这会将字符串转换为原始字符串。 If you do not do this, then Python will look at the backslashes for special characters, such as \\n (new-line), \\t (tab) or \\b (backslash). 如果不这样做,Python会查看反斜杠以查找特殊字符,例如\\n (换行符), \\t (制表符)或\\b (反斜杠)。 You have the latter in your string. 您的字符串中包含了后者。

One way to find out what's going on is to try printing the string in the interpreter. 找出正在发生的事情的一种方法是尝试在解释器中打印字符串。 Take a look at the following example: 看下面的例子:

>>> "C:\Program Files\MySQL\MySQL Server 5.1\bin\mysqladmin"
'C:\\Program Files\\MySQL\\MySQL Server 5.1\x08in\\mysqladmin'

>>> r"C:\Program Files\MySQL\MySQL Server 5.1\bin\mysqladmin"
'C:\\Program Files\\MySQL\\MySQL Server 5.1\\bin\\mysqladmin'

There are two alternatives to using raw strings. 使用原始字符串有两种选择。 The first one is to just escape the backslashes: 第一个是只是逃避反斜杠:

>>> "C:\\Program Files\\MySQL\\MySQL Server 5.1\\bin\\mysqladmin"

I've always found that a bit ugly and somewhat harder to read. 我总是发现它有点丑陋,而且有点难以阅读。 You can also replace the backslashes with forward slashes: 您还可以将反斜杠替换为正斜杠:

>>> "C:/Program Files/MySQL/MySQL Server 5.1/bin/mysqladmin"

This will work, although it looks kind of odd if you're a Windows guy. 这将起作用,尽管如果您是Windows人士,这看起来有些奇怪。 So in the end, I still recommend using raw strings. 所以最后,我仍然建议使用原始字符串。

尝试将\\更改为/ ,它应该可以工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM