我可以在python3中使用perl中类似pipen的选项吗?

2024-04-25 07:22:23 发布

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

如果我在perl中查找文件名模式,您可以执行以下简单操作:

ls -l | perl -n -e'if(/.*180205.*/){ print "$_\n"; }'

-n
causes Perl to assume the following loop around your program, which makes it iterate over filename arguments somewhat like sed -n or awk:

LINE:
  while (<>) {
      ...             # your program goes here
  }

如何在python3中编写代码?(python3--help不显示此选项)


Tags: thetoloopyourif模式programls
1条回答
网友
1楼 · 发布于 2024-04-25 07:22:23

带有python -c '...'的Python oneliner受到极大的限制,因为Python语法假定每个语句都位于自己的行上。可以用分号“;”组合一些语句,但有些语句需要有自己的行,特别是循环之类的复合语句。如果您想在命令行上写这个,我们必须将所有行上的循环表示为一个列表:

python3 -c 'import re, fileinput; [print(line, end="") for line in fileinput.input() if re.search("180205", line)]'

这当然是相当不可读的,因为Python不太适合一行程序。在fileinput.input()上循环类似于Perl的-n选项。你知道吗

如果您想使用Python,可以考虑编写一个脚本。这一点更具可读性:

import re, fileinput
for line in fileinput.input():
    if re.search("180205", line):
        print(line, end="")

相关问题 更多 >