2016-11-28 77 views
0

我想打印出从该行代码的输出换行符:如何设置格式 n在Python

subprocess.check_output('cmd.exe /K cmd',shell=False) 

但输出是这样的

**Microsoft Windows [Version 6.3.9600]\r\n(c) 2013 Microsoft Corporation. All rights reserved.\r\n\r\nC:\\Users\\19leungc8\\Desktop>\r\nC:\\Users\\19leungc8\\Desktop>** 

取而代之:

**Microsoft Windows [Version 6.3.9600]** 

**(c) 2013 Microsoft Corporation. All rights reserved.** 

如果需要,我会提供更多信息。

回答

1

至于subprocess.check_output的文档解释:

默认情况下,这个函数将返回数据为编码字节。输出数据的实际编码可能取决于被调用的命令,因此解码到文本通常需要在应用程序级别进行处理。

所以你得到的是一个bytes对象,它包含你的命令的输出作为编码字节。打印对象时可以看到这个;字节文字在引号前面有一个b都打印时,当打印了repr

>>> x = b'foo bar' 
>>> print(x) 
b'foo bar' 
>>> x  # basically the same as print(repr(x)) 
b'foo bar' 

为了得到正确的串出这一点,你需要解码使用bytes.decode()字节对象。请注意,为了将字节解码为字符串,您需要知道将数据编码为什么编码。非常普遍的情况下,这将是utf-8,在这种情况下,您不需要传递任何参数:

>>> x.decode() 
'foo bar' 
>>> print(x.decode()) 
foo bar 
+0

我已经得到我的代码工作。谢谢你的帮助 –

2

您不必担心。字符串中的\n表示字符串中的新行。如果您打印check_output()的内容,您将看到在控制台中用新行代替\n。例如:

>>> my_text = "1234\n\n1234" 
>>> my_text 
'1234\n\n1234' 
# ^value of `my_text` holds `\n` 

# on printing the `my_text`, `\n` is replaced with new line 
>>> print(my_text) 
1234 

1234 

在你的情况,你应该这样做,如:

my_output = subprocess.check_output(...) 
print(my_output) 
+0

感谢您的回应。你能否在你的帖子下面阅读我的回复? –