简体   繁体   中英

Python one liner for extracting url from text

My goal is to write one liner for extracting URLs from text. The problem is that I'm not even able to read data from STDIN. My experiments so far:

└──> grep -i http: flashgot.log | python -c 'import sys; import re; for line in sys.stdin: print line'
  File "<string>", line 1
    import sys; import re; for line in sys.stdin: print line
                             ^
SyntaxError: invalid syntax


└──> grep -i http: flashgot.log | python -c 'import sys; import re; x = [print line for line in sys.stdin]'
  File "<string>", line 1
    import sys; import re; x = [print line for line in sys.stdin]
                                    ^
SyntaxError: invalid syntax

Second plan was to use some of advises from here here here or here

I got your snippet working by using sys.stdout.write instead of print :

grep -i http: flashgot.log | python -c 'import sys; import re; [sys.stdout.write("%s\n" % line) for line in sys.stdin]'

I think the problem was not with reading stdin but more with finding the correct syntax to use on one line. On trying your scripts, it looks like for doesn't work as a block in the single-line syntax, and neither does print within a list-generator.

PS: While trying one-line functions, I find that lambda comes in handy sometimes. You might find it useful later in your script

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM