Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement bash's vertical bar operator in python console?

I wish i could write like

>>> print many_lines_message | tail -1

in python console, how to do that?

like image 858
scythargon Avatar asked Feb 12 '26 05:02

scythargon


2 Answers

print many_lines_message.splitlines()[-1]

If you want to simulate head, tail and/or grep commands, it is easy with slices and/or list comprehensions.

If you want to do something different, give us more examples.

like image 72
eumiro Avatar answered Feb 14 '26 19:02

eumiro


If you really want to pass the output of an arbitrary Python expression to an external command, you will need to start a process and use a pipe. In bash a pipe is spelt |, in Python the subprocess module can help you with that. But if you just need the example you gave, the answers by eumiro and Jon Clements are what you need.

like image 31
gerrit Avatar answered Feb 14 '26 17:02

gerrit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!