在Python中使用管道

0 投票
1 回答
696 浏览
提问于 2025-04-16 19:36
import re
import subprocess

sub = subprocess.Popen(['/home/karthik/Downloads/stanford-parser-2011-06-   08/lexparser.csh'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr = subprocess.PIPE)

sub.stdin.write("i am a fan of ac milan which is the best club in the world")

relns = []

while(True):
    rel = sub.stdout.readline()
        m = re.search("Sentence skipped", rel)

    if m != None:
            print 'stop'
            sys.exit(0)

        if rel == '\n':
                break
        relns.append(rel) 

print relns

sub.terminate()

我想用斯坦福解析器,并通过lexparser.csh来解析这段文本。但是当我运行这段代码时,输出的却是默认的文本。实际上给定的文本没有被解析。那么我使用管道的方式对吗?我在很多例子中看到,命令后面会加一个'-',这是为什么呢?因为当我使用这个时,脚本在sub.stdout.readline()那里就卡住了。

1 个回答

1

在写完内容后,你可能需要对 sub.stdin 调用 flush() 方法。

撰写回答