Giter Club home page Giter Club logo

xontrib-pipeliner's Introduction

Easily process the lines using pipes in xonsh shell. Multicore processing supported.

If you like the idea of pipeliner click โญ on the repo and tweet.

Install

xpip install -U xontrib-pipeliner
echo 'xontrib load pipeliner' >> ~/.xonshrc
# Reload xonsh

Usage

Let your pipe lines flow thru the Python code:

<cmd> | ... | pl "<lambda expression>" | <cmd> | ...

There are two variables available in lambda expression:

  • line from pipe.
  • num of the line starts with 0.

Experimental features

  • ppl is to run multicore pl. It tested mostly on Linux. See "Known issues" section.
  • plx is the shorter way to execute the commands with pipe lines i.e. ls /home | plx 'du -sh /home/{line}'.

Examples

Python way to line modification

ls -1 / | pl "line + ' is here'" | head -n 3
bin is here
boot is here
dev is here

Line number

ls -1 / | head -n 4 | pl "f'{num} {line}'"
0 bin
1 boot
2 cdrom
3 dev

Ignore line

$ ls -1 / | head -n 4 | pl "f'{num} {line}' if num%2 == 0 else None"
0 bin
2 cdrom

Splitting

cat /etc/passwd | head -n 3 | pl "line.split(':')[6]"
/bin/bash
/usr/sbin/nologin
/usr/sbin/nologin

Imports

import re
cat /etc/passwd | head -n 3 | pl "re.sub('/bin/bash', '/usr/bin/xonsh', line)"
root:x:0:0:root:/root:/usr/bin/xonsh
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin

Arrays

cat /etc/passwd | head -n 3 | pl "line.split(':')" | grep nologin | pl "':'.join(eval(line)[::-1])"
/usr/sbin/nologin:/usr/sbin:daemon:1:1:x:daemon
/usr/sbin/nologin:/bin:bin:2:2:x:bin

Python head

pl "'\\n'.join(list('ABCDEFG'))" | pl "line + ('!' if num%2 else '?')" | grep '!'
B!
D!
F!

Variables and operations chaining

Expression is a lambda function so using variables and operations chaining since Python 3.8+ are available by trick with the walrus operator and the list:

ls -1 / | head -n3 | pl "[s:='b', line.replace(s, s.upper()+')')][-1]"
B)in
B)oot
dev

Execute command with the line

ls / | head -n 3 | pl "execx('du -sh /'+line) or 'Done command with /'+line"
0       /bin
Done command with /bin
840M    /boot
Done command with /boot
4,0K    /cdrom
Done command with /cdrom

Note! If you do the operations with files (i.e. pl "execx(f'mv {line} prefix-{line}')") you could catch TypeError: an integer is required error that relates to wrong access rights to files. Fix it with chmod and chown before pipelining.

Presets

There are default presets:

echo "  1" | pl strip
# 1

echo "1,2,3" | pl split ,
['1', '2', '3']

echo "a,b,c" | pl split , | pl list 0
# a

You can set your own presets:

$XONTRIB_PIPELINER_PRESETS = {
    "upper": "line.upper()",
    "repeat": lambda args: f"line*int({repr(args[0])})"
}

echo 'hello' | pl upper
# HELLO

echo 'hey \nhi ' | pl repeat 3
# hey hey hey
# hi hi hi

Wrap pipeliner to get your own magic

aliases['my_lovely_pl'] = lambda a,i,o: aliases['pl'](["'My lovely ' + "+a[0]], i, o)
aliases['my_parallel_ppl'] = lambda a,i,o: aliases['ppl'](["'My parallel ' + "+a[0]], i, o)
ls / | head -n 3 | my_lovely_pl "line + '!'"
# My lovely bin!
# My lovely boot!
# My lovely cdrom!

ls / | head -n 3 | my_parallel_ppl "line + '!'"
# My parallel boot!
# My parallel cdrom!
# My parallel bin!

Add your most useful solutions to xontrib-pipeliner. PRs are welcome!

Experimental

Syntax highlighting using xonsh prompt

If you're using xonsh prompt and want to use pipeliner with syntax highlighting instead of string there is experimental feature that catch pl @(<python>) calls and uses the expression from the xonsh python substitution as pipeliner argument. Example:

echo echo | pl @(line + '!')
# In the xonsh prompt it's equals to:
echo echo | pl "line + '!'" 

Syntax highlighting using xonsh macros

To avoid writing Python inside the string and get the syntax highlighting there is a tricky way with using xonsh macro:

def py(code):
    return code

echo 123 | pl @(py!(line + '2'))

Multicore pipelining

By default pipeliner works using one CPU core. To use them all in parallel try ppl command:

head /etc/passwd | ppl "str(num) + ' ' + line.split(':')[0]"
1 daemon
0 root
2 bin
4 sync
5 games
8 mail
9 news
6 man
7 lp
3 sys

Note! The order of result lines is unpredictable because lines will be processed in parallel. The num variable contains the real line number.

Pipeliner exec

There are plx and pplx commands to run execx(f"{plx_command}") most shorter way.

For example when you want to rename files you can do it Pythonic way:

mkdir -p /tmp/plx-test && cd /tmp/plx-test
touch 111 222 333 && ls
# 111 222 333

ls | plx "mv {line} prefix-{line}"
# mv 111 prefix-111
# mv 222 prefix-222
# mv 333 prefix-333

ls
# prefix-111 prefix-222 prefix-333

Echo example:

ls | plx 'echo {line} # {num}'
# echo prefix-111 # 0
# prefix-111
# echo prefix-222 # 1
# prefix-222
# echo prefix-333 # 2
# prefix-333

Pipeliner in xsh scripts

By default xsh scripts haven't rc-file with xontribs loading. To add pipeliner to your script just do xontrib load pipeliner before usage.

Known issues in experimental functions

plx: "Bad file descriptor" on huge amount of lines

xonsh/xonsh#4224

On Mac you can't access to the xonsh context (global variables and functions) in the expression. PR is welcome!

ppl: On MacOS multicore pipelining freezes on end

Workaround is to add cat at the end: echo 1 | ppl 'line' | cat. PR is welcome!

Future

Pipeliner should be a part of xonsh and has shortcut and syntax highlighting. For example:

echo 'Pipeliner should be ' | pl @{line + 'a part of xonsh!'}
# or
echo 'Pipeliner should be ' | ~(line + 'a part of xonsh!')
Pipeliner should be a part of xonsh!

If you want to support this in xonsh add your Like and support message to Python code substitution in subproc mode.

Links

xontrib-pipeliner's People

Contributors

anki-code avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

xontrib-pipeliner's Issues

Pipeline that takes full stream

Would be nice if there was a mode where lambda argument instead of line-by-line was a file object for the whole input stream.

@( ) inconsistent

Hi!

I'm playing with xonsh and this contrib is really useful to leverage it.

I detected some inconsistencies with the experimental feature @(). The following can help polish it.

The ls | pl @( line ) works as it's expected but not ls | pl @( line.upper() ). However, ls | pl @( (lambda l: l.upper())(line) ) does.

Does not work with bashisms loaded

Thanks for the useful snippet.

I tried this plugin with bashisms loaded but couldn't get it to work. When I do echo "hello world" | pl "line". It is stuck forever and doesn't print anything.

After removing bashishms from xontrib load, it is working as expected. I read the bashishms source code but couldn't figure out the conflicting piece of code.

OSX: ppl โ€” NameError: name '__xonsh__' is not defined

I'm trying to use ppl with this pipe find . | ppl "str(num) + ' ' + line" and get error.

any idea how to fix it?

~/D/C/book $ XONSH_SHOW_TRACEBACK = True
~/D/C/book $ find . | ppl "str(num) + ' ' + line"
xonsh: To log full traceback to a file set: $XONSH_TRACEBACK_LOGFILE = <filename>
multiprocessing.pool.RemoteTraceback:
"""
Traceback (most recent call last):
  File "/usr/local/Cellar/[email protected]/3.9.2_4/Frameworks/Python.framework/Versions/3.9/lib/python3.9/multiprocessing/pool.py", line 125, in worker
    result = (True, func(*args, **kwds))
  File "/usr/local/Cellar/xonsh/0.9.27/libexec/lib/python3.9/site-packages/xontrib/pipeliner_parallel.py", line 28, in __call__
    return self.f(x)
  File "/usr/local/Cellar/xonsh/0.9.27/libexec/lib/python3.9/site-packages/xontrib/pipeliner_parallel.py", line 10, in f
    ctx = __xonsh__.ctx
NameError: name '__xonsh__' is not defined
"""

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/local/Cellar/xonsh/0.9.27/libexec/lib/python3.9/site-packages/xonsh/procs/proxies.py", line 508, in run
    r = self.f(self.args, sp_stdin, sp_stdout, sp_stderr, spec, spec.stack)
  File "/usr/local/Cellar/xonsh/0.9.27/libexec/lib/python3.9/site-packages/xonsh/procs/proxies.py", line 305, in proxy_three
    return f(args, stdin, stdout)
  File "/usr/local/Cellar/xonsh/0.9.27/libexec/lib/python3.9/site-packages/xontrib/pipeliner.py", line 65, in _ppl
    xppl.go(func_args, stdout)
  File "/usr/local/Cellar/xonsh/0.9.27/libexec/lib/python3.9/site-packages/xontrib/pipeliner_parallel.py", line 23, in go
    for result in parallel_tasks:
  File "/usr/local/Cellar/[email protected]/3.9.2_4/Frameworks/Python.framework/Versions/3.9/lib/python3.9/multiprocessing/pool.py", line 870, in next
    raise value
NameError: name '__xonsh__' is not defined

Maybe have to import builtins?

import builtins

Piping to ppl does not return on Mac

Trying pipeliner on a Mac and the command never returns.

This does not return:

> echo 1 | ppl 'line'

Neither does this:

> echo 1 | ppl 'line' | cat
> xonfig
+------------------+----------------------+
| xonsh            | 0.10.1               |
| Git SHA          | 337cf25a             |
| Commit Date      | Nov 17 15:37:41 2021 |
| Python           | 3.9.9                |
| PLY              | 3.11                 |
| have readline    | True                 |
| prompt toolkit   | 3.0.24               |
| shell type       | prompt_toolkit       |
| history backend  | json                 |
| pygments         | 2.11.2               |
| on posix         | True                 |
| on linux         | False                |
| on darwin        | True                 |
| on windows       | False                |
| on cygwin        | False                |
| on msys2         | False                |
| is superuser     | False                |
| default encoding | utf-8                |
| xonsh encoding   | utf-8                |
| encoding errors  | surrogateescape      |
| on jupyter       | True                 |
| jupyter kernel   | None                 |
| xontrib 1        | bashisms             |
| xontrib 2        | coreutils            |
| xontrib 3        | jedi                 |
| xontrib 4        | pipeliner            |
| xontrib 5        | pyenv                |
| xontrib 6        | sh                   |
| xontrib 7        | vox                  |
| xontrib 8        | vox_tabcomplete      |
| xontrib 9        | voxapi               |
+------------------+----------------------+

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.