0

Let's say I want to do an ls command and then use python's re library to filter the results, the equivalent of this

$ ls|grep c
cmd.py

Is this possible to do across pipes? For example, something like this:

$ ls|python -c "import re,sys;r=re.search('^c', sys.argv[0]); print (r.group(1))"
                                                   ^
                                            #   'pretending' the output of `ls` is passed in sys.argv

Is this possible to do without a lot of legwork (such as reading/writing to a file)?

David542
  • 104,438
  • 178
  • 489
  • 842
  • 1
    Use `sys.stdin` https://docs.python.org/3/library/sys.html#sys.stdin – flakes Sep 04 '20 at 04:10
  • 1
    `sys.argv` is command line arguments, not input. – Barmar Sep 04 '20 at 04:17
  • @flakes cool that worked, thanks for the suggestion (put in the answer below). – David542 Sep 04 '20 at 04:17
  • The *question* [here](/questions/7091413/how-do-you-read-from-stdin-in-python-from-a-pipe-which-has-no-ending) seems to answer your question. – Karl Knechtel Sep 04 '20 at 04:17
  • **Don't filter `ls`.** It's fundamentally unreliable. Python already has `os.listdir` - use that instead. – user2357112 Sep 04 '20 at 04:18
  • @user2357112supportsMonica right, the above example is just made up. I'm just using this as what I thought would be the most basic way of showing how to do a pipe from a cmd to python. – David542 Sep 04 '20 at 04:19
  • @KarlKnechtel not really, I want to limit everything to the command line and a very terse one-liner, though I understand the duplicate discusses reading from stdin. – David542 Sep 04 '20 at 04:21

1 Answers1

0

From @flakes comment you can use stdin to get the input data. For example:

$ ls|python -c "import re,sys;r=re.search(r'c.+', sys.stdin.read()); print (r.group())"
# cmd.py
David542
  • 104,438
  • 178
  • 489
  • 842
  • No need to use a raw string `r''` there. You're not using any escaped characters in the regex. i.e backslashes – flakes Sep 04 '20 at 04:19
  • 1
    @flakes It's a good habit to always use a raw string for regexp. There's no harm if it doesn't contain any escape sequences. – Barmar Sep 04 '20 at 04:19
  • @flakes -- thanks, at this point it's really just a habit and whenever I write a regex I use it (my editor even highlights the regex text different than a normal string). Is there any downside for using it though when no escapes are needed? – David542 Sep 04 '20 at 04:20
  • @Barmar that's fair, seems reasonable enough. I usually opt to use the least amount of features required by the code. (e.g. flake8 now will yell at you if you use an f-string `f""` without any formats `{...}` used). Is there any PEP around that rule? – flakes Sep 04 '20 at 04:22