简体   繁体   English

控制台o / p数据到日志文件的格式未格式化(Python脚本)

[英]Console o/p data to log file is not formatted (Python script)

I have a python script using which I call a command that lauches a software (which runs a simulation) and then after completion the simu software is closed. 我有一个python脚本,使用该脚本我会调用一个启动软件的命令(运行模拟程序),然后在完成后关闭simu软件。 The simulation s/w has a console window on which some o/p is displayed. 模拟软件具有一个控制台窗口,在该窗口上显示一些o / p。

If I would have launched this simu manually using a shell without then I can also see the o/p of this simu s/w console window in the shell. 如果我不使用外壳就可以手动启动此Simu,那么我也可以在外壳中看到此Simu s / w控制台窗口的o / p。

My primary target is to write this console window o/p to a log file. 我的主要目标是将此控制台窗口o / p写入日志文件。

Hence I did the following and it is working. 因此,我做了以下工作,并且正在工作。

import commands
logging.basicConfig(...)
.
.
.    
simu_cmd = "my_cmd"
logging.info(commands.getstatusoutput(simu_cmd))
.
.

Now when I open my log file after the python script completes execution, then I see the complete expected o/p written out in the log file. 现在,当我在python脚本完成执行之后打开日志文件时,我会在日志文件中看到完整的预期o / p。

But there is NO FORMATTING of the data. 但是没有数据的格式。 It is just like a big string printed one after the other. 就像一个大串接一个的打印。 There are spaces in between words, but are problems with 'new lines'. 单词之间有空格,但是“换行”存在问题。 I can even see '\\n' and '\\r' characters in my log files. 我什至可以在日志文件中看到“ \\ n”和“ \\ r”字符。

Can anyone please suggest how to I write the formatted output to the log file or improve on the code I have written? 谁能建议我将格式化后的输出写入日志文件或改善我编写的代码吗?

Note- May be I am using an old process to write out to a log file, but I want to keep it stupid and simple. 注意-可能是我正在使用旧的过程写出到日志文件,但是我想保持它的愚蠢和简单。 In some thread here some people have mentioned the useage of subprocess(), but it looked complicated to me. 在这里的某些线程中,有人提到了subprocess()的用法,但对我来说,它看起来很复杂。 I will always be using a Linux m/c. 我将始终使用Linux m / c。

You are logging the result of commands.getstatusoutput() which is not just the output of the command but a tuple with two elements — the status value and the output of the command. 您正在记录commands.getstatusoutput()的结果,该结果不仅是commands.getstatusoutput()的输出,而且是具有两个元素的元组 -状态值和命令的输出。 If you log that tuple you will get the string representation of that tuple and strings in tuples are converted with the repr() function into the string representation within the tuple. 如果您记录该元组,则将获得该元组的字符串表示形式,并且元组中的字符串将通过repr()函数转换为该元组中的字符串表示形式。

Here is an example of the difference: 这是区别的示例:

In [27]: result = (0, 'one\ntwo')

In [28]: print result
(0, 'one\ntwo')

In [29]: print result[1]
one
two

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

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