ubuntu@ubuntu:/home/ubuntuUser$ cat test.txt
This is a test file
used to validate file handling programs
#pyName: test.txt
this is the last line
ubuntu@ubuntu:/home/ubuntuUser$ cat test.txt | grep "#pyName"
#pyName: test.txt
ubuntu@ubuntu:/home/ubuntuUser$ "
#1 >>> a = subprocess.Popen(['cat test.txt'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
#2 >>> o, e = a.communicate(input='grep #pyName')
#3 >>> print o
#3 This is a test file
#3 used to validate file handling programs
#3 #pyName: test.txt
#3 this is the last line
#3
#3 >>>
问题:
问题1: 文件上的shell grep命令只打印匹配的行,而grep via子进程打印整个文件。怎么了?在
问题2:
如何将通过communicate()发送的输入添加到
初始命令('cat测试.txt')?
在#2
之后,在“|”和shell命令变得像cat test.txt | grep #pyName
之后,初始命令是否会被来自communicate的输入字符串追加?在
你在这里做的基本上是
cat test.txt < grep ...
,这显然不是你想要的。要设置管道,需要启动两个进程,并将第一个进程的stdout连接到第二个进程的stdin:也许将
grep
传递给communicate()
-函数并不像您假设的那样工作。可以通过直接从文件中重新映射来简化过程,如下所示:用python做你想做的事情可能会更聪明。如果您的行在文件中,下面将打印它。在
^{pr2}$@prasath如果您正在寻找使用communicate()的示例
相关问题 更多 >
编程相关推荐