简体   繁体   English

如何获得命令提示符输出? 为什么我不能在这段代码中得到它

[英]How to get command prompt output? Why can't I get it in this code

I try to get string in command prompt by the way using "subprocess". 我尝试使用“子进程”在命令提示符下获取字符串。 The execution contents is to read "TOC" of CD-DA.I'm using "cdparanoia". 执行内容是读取CD-DA的“ TOC”。我正在使用“ cdparanoia”。 In case of keyin on command prompt I can get "TOC". 在命令提示符下键入的情况下,我可以获得“ TOC”。

import subprocess
class Aaa():
    def __init__(self):
        p = subprocess.Popen("cd-paranoia",stdout=subprocess.PIPE)
        out = p.communicate()[0]
        str = out.decode(encode="utf-8")
        print(str)
Aaa()

In the above code, it's displayed red string of "TOC" pressing reset button on interactive window in Visual Studio 2017. But it can't be stored in variable "str". 在上面的代码中,在Visual Studio 2017的交互式窗口中,按下重置按钮后,会显示红色字符串“ TOC”。但是无法将其存储在变量“ str”中。 What should I do? 我该怎么办?

Processes can choose to output to output or error streams. 进程可以选择输出到输出或错误流。 In your case you're not redirecting the error stream. 在您的情况下,您不会重定向错误流。 You can for instance merge both output & error streams like this: 例如,您可以像这样合并输出和错误流:

    p = subprocess.Popen("cd-paranoia",stdout=subprocess.PIPE,stderr=subprocess.STDOUT)

and the rest of your code does the job. 其余的代码就可以完成工作。

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

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