Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Lập Trình Bash

Marcel: Modern Shell Được Đẩy Bằng Python cho Linux

Marcel là shell mới. Tương tự traditional shells nhiều ways, nhưng làm khác biệt vài điều:

  • Piping: Tất cả shells dùng pipes send text từ output command này đến input command khác. Marcel pipes structured data thay vì strings.
  • Python: Marcel implemented in Python, expose Python nhiều ways. Nếu cần logic trong commands, marcel cho phép express nó trong Python.
  • Scripting: Marcel unusual approach scripting. Có thể write sequence marcel commands trong text file execute. Nhưng Marcel cũng cung cấp API dạng Python module. Import module này để làm Python scripting convenient hơn plain Python.

Marcel licensed under GPLv3.

Cài đặt Marcel Modern Shell trên Linux

Marcel yêu cầu Python 3.6 trở lên. Developed và tested trên Linux, mostly works trên macOS. (Muốn help port to Windows hoặc fix macOS deficiencies, get in touch.)

Cài marcel cho own use:

# python3 -m pip install marcel

Hoặc install for all users (e.g., to /usr/local):

$ sudo python3 -m pip install --prefix /usr/local marcel

Sau khi cài marcel, check working bằng chạy command marcel, rồi tại marcel prompt chạy version command:

$ marcel
Marcel: Modern Shell Được Đẩy Bằng Python cho Linux

Tùy chỉnh Marcel Shell

Tùy chỉnh marcel trong file ~/.marcel.py, được read on startup (và reread khi modified). Từ tên file, customization marcel done in Python.

Điều bạn probably muốn: customize prompt. Assign list to PROMPT variable. Ví dụ: prompt là current directory in green, theo sau > in blue:

PROMPT = [ Color(0, 4, 0), lambda: PWD, Color(0, 2, 5), '> ' ]

Prompt kết quả trông như:

Marcel: Modern Shell Được Đẩy Bằng Python cho Linux

Thay thế PS1 configuration inscrutable cần trong bash. Color(0, 4, 0) specify green (arguments RGB values, range 0-5). PWD là environment variable representing current directory, prefix với lambda: generate function, evaluated mỗi khi prompt displayed.

File ~/.marcel.py cũng import Python modules. Ví dụ: muốn dùng functions của math module trong marcel commands:

from math import *

Sau đó refer symbols từ module, e.g. pi:

Marcel: Modern Shell Được Đẩy Bằng Python cho Linux Marcel: Modern Shell Được Đẩy Bằng Python cho Linux

Lưu ý pi parenthesized. Overall, marcel dùng parentheses delimit Python expressions. So (pi) evaluate Python expression retrieve value của variable pi. Cũng access traditional environment variables cách này, e.g. (USER) và (HOME), hoặc any valid Python expression relying on symbols in marcel's namespace.

Define own symbols. Ví dụ: put function definition này trong ~/.marcel.py:

def factorial(n):
  f = 1
  for i in range(1, n + 1):
    f *= i
  return f

Sau đó dùng factorial function trên command line, e.g.

Marcel: Modern Shell Được Đẩy Bằng Python cho Linux Marcel: Modern Shell Được Đẩy Bằng Python cho Linux

Marcel Shell Examples

Học examples commands trong marcel shell.

Find File Sizes by Extension

Explore current directory recursively, group files by extension (e.g. .txt, .py), compute total file size each group.

Trong marcel làm như sau:

Marcel: Modern Shell Được Đẩy Bằng Python cho Linux

Ls operator produces stream of File objects (-fr visit directories recursively, return only files).

File objects piped đến next command, map. Map specify Python function, outermost parentheses, map each file to tuple chứa file's extension và size. (Marcel cho phép omit lambda keyword).

Red (reduce) operator, group by first part của tuple (extension) và sum up sizes within each group. Result sorted by extension.

Host Executables và Marcel Pipeline

Pipelines có thể contain mixture marcel operators và host executables. Operators pipe objects, nhưng tại operator/executable boundaries, marcel pipe strings instead.

Ví dụ: command kết hợp operators và executables list usernames của users shell là /bin/bash.

$ cat /etc/passwd \
 | map (line: line.split(':')) \
 | select (*line: line[-1] == '/bin/bash') \
 | map (*line: line[0]) \
 | xargs echo
Marcel: Modern Shell Được Đẩy Bằng Python cho Linux Marcel: Modern Shell Được Đẩy Bằng Python cho Linux

Cat là Linux executable. Đọc /etc/passwd, marcel pipe contents downstream đến marcel operator map.

Parenthesized argument to map là Python function split lines tại : separators, yield 7-tuples. Select là marcel operator argument là Python function identify tuples last field là /bin/bash.

Next operator, another map keep username field của each input tuple. Cuối cùng, xargs echo combine incoming usernames into single line, print to stdout.

Scripting trong Marcel Shell

Mặc dù Python sometimes considered scripting language, nó không actually work well cho purpose đó. Problem: running shell commands và other executables từ Python cumbersome. Dùng os.system() simple nhưng often inadequate deal với stdin, stdout, stderr. subprocess.Popen() powerful hơn nhưng complex hơn.

Marcel approach: cung cấp module integrate marcel operators với Python's language features. Revisit earlier example, Python code compute sum file sizes by extension:

from marcel.api import *
for ext, size in (ls(file=True, recursive=True) | map(lambda f: (f.suffix, f.size)) | red('.', '+')):
  print(f'{ext}: {size}')

Shell commands same as before, except syntactic conventions. So ls -fr thành ls(file=True, recursive=True). Map và red operators cũng có, connected với pipes, như shell version. Entire shell command (ls ... red) yield Python iterator để command used với Python's for loop.

Database Access với Marcel Shell

Integrate database access với marcel pipelines. First, configure database access trong config file ~/.marcel.py, e.g.

define_db(name='jao', driver='psycopg2', dbname='acme', user='jao')
DB_DEFAULT = 'jao'

Configure access đến Postgres database acme, dùng psycopg2 driver. Connections từ marcel made using jao user, database profile named jao. (DB_DEFAULT specify jao database profile as one used nếu no profile specified.) Với config done, database queried dùng sql operator, e.g.

sql 'select part_name, quantity from part where quantity < 10' \
 | out --csv --file ~/reorder.csv

Command query table part, dump query result vào file ~/reorder.csv, CSV format.

Remote Access với Marcel Shell

Tương tự database access, remote access configured in ~/.marcel.py. Ví dụ: configure 4-node cluster:

define_remote(name='lab', user='frankenstein', identity='/home/frankenstein/.ssh/id_rsa', host=['10.0.0.100', '10.0.0.101', '10.0.0.102', '10.0.0.103'])

Cluster identified as a lab trong marcel commands. User và identity parameters specify login info, host parameter specify IP addresses nodes trên cluster.

Cluster configured, all nodes operated on at once. Ví dụ: get list process pids và command lines across cluster:

@lab [ps | map (proc: (proc.pid, proc.commandline))]

Return stream of (IP address, PID, command line) tuples.

Thêm thông tin:

Marcel pretty new và under active development. Get in touch nếu muốn help out.