获取子进程的输出而不使用垃圾袋

2024-05-14 19:46:16 发布

您现在位置:Python中文网/ 问答频道 /正文

TranscryptPython to JavaScript编译器中, 我使用以下代码通过子流程传递数据:

                process = subprocess.Popen (
                    [node.args [1] .s],
                    shell = True,
                    stdin = subprocess.PIPE,
                    stdout = subprocess.PIPE
                )
                process.stdin.write (sourceCode.encode ('utf8'))
                process.stdin.close ()
                while process.returncode is None:
                    process.poll ()
                targetCode = process.stdout.read (). decode ('utf8'). replace ('\r\n', '\n')

我的子进程是一个Windows.bat文件,其中包含:

^{pr2}$

内容大写.py是:

import sys
content = sys.stdin.read ()
sys.stdout.write (content.upper ())

如果变量sourceCode最初包含:

dit
is
een
test

因此,变量targetCode将包含:

    D:\activ_tosh\geatec\transcrypt\qquick\Transcrypt\transcrypt\development\experiments\pipe>python capitalize.py 

    D:\activ_tosh\geatec\transcrypt\qquick\Transcrypt\transcrypt\development\experiments\pipe>call D:\python36_anaconda\python.exe capitalize.py 

        DIT
        IS
        EEN
        TEST

换言之,命令的回显被预先添加到stdout中,这是可以预期的。

如果我用echo off启动命令文件,则会得到回显,因此没有帮助。

如何更改的代码子流程.Popen(或其周围的代码)使targetCode只包含:

        DIT
        IS
        EEN
        TEST

我做了很多事情,包括在不同的地方使用echo off,以及重新分配标准输出。我在谷歌上搜索了很多,但没有找到解决办法。有人知道怎么解决这个问题吗?

[编辑1] @马赫什·卡里亚

我试过了:

                process = subprocess.Popen (
                    [node.args [1] .s],
                    shell = True,
                    stdout = subprocess.PIPE
                )
                print (111)
                targetCode = process.communicate (io.StringIO (sourceCode))[0]
                print (222)

这在打印111后挂起。

[编辑1]

我已经通过使用一个可执行文件(从C++翻译)作为一个过滤器来解决我的问题,而不是.BAT或.pY文件。这不会生成任何控制台回显。

#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

int main () {
    string buffer;
    getline (cin, buffer, '\f');
    transform (buffer.begin(), buffer.end(), buffer.begin(), ::toupper);
    cout << buffer;
}

如果输入的数据结束字符'f'

'''
<div id="StudentContainer">
    {self.props.students.map((s) => (
        <StudentTile student={s}  key={s.searchval}  />
    ))}
</div>
\f'''

Tags: 文件代码pyincludebufferstdinstdoutsys
1条回答
网友
1楼 · 发布于 2024-05-14 19:46:16

一种方法是使用communicate()获取输出。在

processes = [Popen(cmd, shell=True, stdout=subprocess.PIPE) for cmd in self.cmd_list]
for p in processes: p.wait()
for p in processes:
    output = p.communicate()[0]
    print output

相关问题 更多 >

    热门问题