首页 > 解决方案 > 如何在标准输入的 python 条件下也只读取一行

问题描述

我将以下数据传递给 stdin stdout :

aa 
a
aaa 
aaaaa
[new,aaa] < name of the file with path ] 
orem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap
[mod] <name of the file with path 
orem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap

我只想复制带有 python 路径的文件名。

if new keyword exists in stdin: 
      take the filename with path
else
      nothing.

标签: pythonstdout

解决方案


您从标准输入读取,而不是标准输出。如果您将另一个程序的输出通过管道传输到 Python 脚本,它将位于 Python 的标准输入中。

您可以使用正则表达式来提取文件名。

import re
import sys

regex = re.compile(r'\[[^]]*new.*?\].*<\s*(.*?)\s*\]')

for line in sys.stdin:
    m = regex.search(line)
    if m:
        filename = m.group(1)
        break

推荐阅读