From charlesreid1

(Created page with "Here's the trick to using python as a one liner: <code>sys.stdin.read()</code> <pre> echo "zero one two three" | python -c 'import sys; print(sys.stdin.read().split(" ")[2])...")
 
No edit summary
 
(2 intermediate revisions by the same user not shown)
Line 1: Line 1:
Here's the trick to using python as a one liner: <code>sys.stdin.read()</code>
Here's the trick to using python as a one liner: <code>sys.stdin.read()</code>
===quick example===


<pre>
<pre>
Line 8: Line 10:


The Python takes everything from stdin and reads it into a string, turns it into a list by splitting at spaces, and prints the third item in the list.
The Python takes everything from stdin and reads it into a string, turns it into a list by splitting at spaces, and prints the third item in the list.
===parsing json===
To parse json, use <code>-m json.tool</code>:
<pre>
$ curl "https://git.charlesreid1.com/api/v1/user/repos?access_token=a936efc887b1947561ab901d08abe3b3b3128a80" | python -m json.tool
</pre>
===exit codes===
To illustrate the difference in how bash treats exit codes: 0 means process completed normally/successfully, 1 means error:
(Note: In bash, <code>&&</code> means "only run this code if the prior command succeeds.")
<pre>
$ python && echo "hello world"
>>> import sys
>>> sys.exit(0)
hello world
$
</pre>
<pre>
$ python && echo "hello world"
>>> import sys
>>> sys.exit(1)
$
</pre>
[[Category:One-Liners]]
[[Category:Python]]
[[Category:JSON]]
[[Category:Shell]]
[[Category:Unix]]

Latest revision as of 18:28, 6 November 2018

Here's the trick to using python as a one liner: sys.stdin.read()

quick example

echo "zero one two three" | python -c 'import sys; print(sys.stdin.read().split(" ")[2])

Above, we print sample output and pipe it to a python program..

The Python takes everything from stdin and reads it into a string, turns it into a list by splitting at spaces, and prints the third item in the list.

parsing json

To parse json, use -m json.tool:

$ curl "https://git.charlesreid1.com/api/v1/user/repos?access_token=a936efc887b1947561ab901d08abe3b3b3128a80" | python -m json.tool


exit codes

To illustrate the difference in how bash treats exit codes: 0 means process completed normally/successfully, 1 means error:

(Note: In bash, && means "only run this code if the prior command succeeds.")

$ python && echo "hello world"
>>> import sys
>>> sys.exit(0)
hello world
$ 


$ python && echo "hello world"
>>> import sys
>>> sys.exit(1)
$