Python Forum

Full Version: run python in commands easier
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
this is the code designed for a unix/linux interactive shell. i have no way to try it on windows. so i have no way to know if it could work in the windows command line.

px.py:
#!/usr/bin/env python3
import os,sys
if len(sys.argv)>1:os.execvp('/usr/bin/env',['env','python3','-c','\n'.join(sys.argv[1:])])
that's it! just 3 lines! do whatever your system needs done to make it be an executable command. i made mine be the command "px" in /usr/local/bin/px. so now you can write python code at the command line, even in pipelines. this is the kind of thing i have used awk for, for the past 3 decades. now i can do it in python. you could already do this with the -c option on the python command. but you had to put a real newline in the argument string after each line but the last. this 3 line code does it for you. just put each line of code to run in your command in a separate argument. and don't forget indentation. python still uses it, even this way.

here is a sample that duplicates lines (a rather silly goal) and then has cat number them:

ls -l /etc|px 'import sys' 'for x in sys.stdin:' ' print(x+x,end="")'|cat -n
you can figure out what you could use it for. i used it a short while ago to split a list of files by the '/' character and extract the 3rd component directory to be piped to a command that counts them up a reports how many of each it saw. i probably could have done it another way, but doing it with python feels better, now.