【问题标题】:Can I use in python3 something like -n pipe-option in perl?我可以在 python3 中使用 perl 中的 -n pipe-option 之类的东西吗?
【发布时间】:2018-02-09 22:54:08
【问题描述】:

如果我在 perl 中查找文件名模式,您可以这样做:

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

-n
导致 Perl 在您的程序周围假设以下循环,这使得它迭代文件名参数,有点像 sed -nawk

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

如何在 python3 中编写代码? (python3 --help 显示不是这样的选项)

【问题讨论】:

  • 你是在命令行上设置还是 python 代码会这样做?
  • 你可以通过 perl -n -E 'say if /180205/ 大大缩短 Perl 程序
  • 对于熟悉 Python 但不熟悉 Perl 的任何人,您可能想描述一下 -n 的确切作用。
  • 其实perl --help-n 的意思是假设“while () { ... }” 循环程序
  • 既然可以ls -l *180205*,为什么还需要perl或python?

标签: python python-3.x perl


【解决方案1】:

带有python -c '...' 的Python oneliners 受到极大限制,因为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="")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-08
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多