2 ms·
Funnily, I was thinking about this the other day with Python: python is great for scripting, with the generators, string formatting and stlib modules like pathl
by BiteCode_dev 5y ago
Funnily, I was thinking about this the other day with Python: python is great for scripting, with the generators, string formatting and stlib modules like pathlib, datetime or argparse.
But there are still stuff I use bash for because it's way more efficient for one liners and small utilities.
One of the things is that calling something in bash autoprints, unless you pipe it. Could it be done in Python?
Well, it turns out you can, if you do a little dirty hacking with __call__, __repr__, __iter__, __or__ and __del__, you get:
https://0bin.net/paste/XeMvMuSh#45izWhAtQ5Bd14PDWoBqTJMvHZXayl-dTtCyQbmxGpU https://0bin.net/paste/XeMvMuSh#45izWhAtQ5Bd14PDWoBqTJMvHZXa...
Which will let you do:
-ls('/etc'), auto prints all the files in the dir, in the shell and in a program.
- ls('/etc') | keep(r'\.conf$'), pipe the output of ls, pass it to keep, filter it, then auto print it (again, works in the shell AND in a py file)
- res = ls('/etc') | keep(r'\.conf$'), store the generator in the variable, doesn't print, doesn't calculate, ready to be able to be read with a for loop
This means we could create a lib with a very shell like experience in python for all those 5-lines-scripts that are still too good to pass bash for.
We could also make a @main decorator to auto run a function if __name__ == "__main__", borrow the "with cd()" and "with temp()" syntax from the fabric lib.
The need for bash would get smaller and smaller for me. I rarely develop on a linux box that doesn't have python, after all.
Now a problem people often hit is: yes, but you have to provide the dependency to your script. ShellJS proves that despite that, it has a great value already.
But the good news is, it's not a problem anymore thanks to a great features of Python 3: zipapps. With shiv (https://shiv.readthedocs.io/en/latest/ https://shiv.readthedocs.io/en/latest/), you can bundle your python script and all its dependencies (including our dirty shell lib) in a single pyz file, which then can run anywhere there is a modern python, which is everywhere I personally need it.