Enjoyable scripting experience with Python

Overview

shx

PyPI version

Inspired by zx

#!/usr/bin/env shx

await $"cat setup.py | grep name"

branch = await $("git branch --show-current", capture='o')
await $f"dep deploy --branch={branch}"

await gather(
  $"sleep 1; echo 1",
  $"sleep 2; echo 2",
  $"sleep 3; echo 3",
)

name = "foo bar"
await $f"mkdir /tmp/{Q(name)}"

(Take a look at more examples.)

shx makes your script writing experience better by taking the advantages of Python's sugary syntax, AsyncIO, and the extensive Python ecosystem. shx does three things:

  1. Wrap asyncio.create_subprocess_shell around with a syntax sugar. await $"command" returns an asyncio.subprocess.Process instance; on non-zero return code, raise subprocess.CalledProcessError.
  2. Provide a top-level async environment.
  3. Preload commonly used imports and utilities. Currently, the imports are:
import asyncio
from asyncio import *
from pathlib import Path
from shlex import quote as Q
import shutil

Note that shx does not perform quote escape automatically. Use function Q (alias of shlex.quote) to escape unsafe arguments.

Install

pip install shx

Settings and utility functions

Settings can either be task local (e.g. __.trace = True) or per-command (e.g. await $("echo 42", trace=True)):

  • shell (Default: $(which bash)): Shell to be used.
  • prefix (Default: set -euo pipefail;): String to be prepended to a command.
  • trace (Default: True): Display command if set to True. Same as set -x in bash.
  • capture (Default: False): If set to True, capture stdout and stderr instead of displaying them. The captured strings will replace the .stdout and .stderr attributes of the asyncio.subprocess.Process instance returned. await $("...", capture='o') and await $("...", capture='e') are the aliases of (await $("...", capture=True)).stdout and (await $("...", capture=True)).stderr, respectively.

Attributes:

  • __.argv: alias of sys.argv, a list of command line arguments
  • __.env: alias of os.environ, a dict of environment variables

cd(cwd: str)

Change working directory to cwd. Same as the task local settings, the changes are only effective within the current task.

question(prompt: str)

input() with KeyboardInterrupt handling.

About the subprocess syntax

No magic, no meta-programming, and no hacking, whatsoever. Prior execution, the script is tokenized, and the following replacements occur:

  • "str prefix" $"command" -> SHX("command")
  • "function" $("command", k1=v1, ...) -> SHX("command", k1=v1, ...)

where SHX is an async function wrapping around asyncio.create_subprocess_shell.

You might also like...
PyDy, short for Python Dynamics, is a tool kit written in the Python
PyDy, short for Python Dynamics, is a tool kit written in the Python

PyDy, short for Python Dynamics, is a tool kit written in the Python programming language that utilizes an array of scientific programs to enable the study of multibody dynamics. The goal is to have a modular framework and eventually a physics abstraction layer which utilizes a variety of backends that can provide the user with their desired workflow

A Python script made for the Python Discord Pixels event.

Python Discord Pixels A Python script made for the Python Discord Pixels event. Usage Create an image.png RGBA image with your pattern. Transparent pi

this is a basic python project that I made using python

this is a basic python project that I made using python. This project is only for practice because my python skills are still newbie.

Analisador de strings feito em Python // String parser made in Python

Este é um analisador feito em Python, neste programa, estou estudando funções e a sua junção com "if's" e dados colocados pelo usuário. Neste código,

Python with braces. Because Python is awesome, but whitespace is awful.

Bython Python with braces. Because Python is awesome, but whitespace is awful. Bython is a Python preprosessor which translates curly brackets into in

PSP (Python Starter Package) is meant for those who want to start coding in python but are new to the coding scene.

Python Starter Package PSP (Python Starter Package) is meant for those who want to start coding in python, but are new to the coding scene. We include

Py-Parser est un parser de code python en python encore en plien dévlopement.

PY - PARSER Py-Parser est un parser de code python en python encore en plien dévlopement. Une fois achevé, il servira a de nombreux projets comme glad

Simple, high-school-leveled sequence library written in Python / 간단한 고등학교 수준 수열 라이브러리 (Python)
A community based economy bot with python works only with python 3.7.8 as web3 requires cytoolz

A community based economy bot with python works only with python 3.7.8 as web3 requires cytoolz has some issues building with python 3.10

Owner
null
HSPyLib is a Python library that will elevate your experience to another level.

HomeSetup Python Library - HSPyLib Your mature python application HSPyLib is a Python library that will elevate your experience to another level. It r

Hugo Saporetti Junior 4 Dec 14, 2022
Google Foobar challenge solutions from my experience and other's on the web.

Google Foobar challenge Google Foobar challenge solutions from my experience and other's on the web. Note: Problems indicated with "Mine" are tested a

Islam Ayman 6 Jan 20, 2022
This repo is related to Google Coding Challenge, given to Bright Network Internship Experience 2021.

BrightNetworkUK-GCC-2021 This repo is related to Google Coding Challenge, given to Bright Network Internship Experience 2021. Language used here is py

Dareer Ahmad Mufti 28 May 23, 2022
Extra scripts to improve user experience related to OpenTaiko

OpenTaiko-Utils Extra scripts to improve user experience related to OpenTaiko osu2tja /!\ IMPORTANT NOTE /!\ Converted charts that aren't yours are fo

null 2 Dec 25, 2022
JPMC Virtual Experience

This repository contains the submitted patch files along with raw files of the various tasks assigned by JPMorgan Chase & Co. through its Software Engineering Virtual Experience Program on Forage (formerly Inside Shepra).

Vardhini K 1 Dec 5, 2021
Fithub is a website application for athletes and fitness enthusiasts of all ages and experience levels.

Fithub is a website application for athletes and fitness enthusiasts of all ages and experience levels. Our website allows users to easily search, filter, and sort our comprehensive database of over 100 exercise types to connect with related equipment and fitness Youtubers. The data is obtained by using eBay and youtube APIs and stored in a mongoDB database

Andrew Wu 1 Dec 13, 2021
A tool for RaceRoom Racing Experience which shows you launch data

R3E Launch Tool A tool for RaceRoom Racing Experience which shows you launch data. Usage Run the tool, change the Stop Speed to whatever you want, and

Yuval Rosen 2 Feb 1, 2022
Better Giveaways is a bot that will change the experience of using a giveaway bot forever.

Better-Giveaways Better Giveaways is a bot that will change the experience of using a giveaway bot forever. VoxelBotUtils/Novus, latest PyPi releases

Lightning 2 Jan 12, 2022
Thumbor-bootcamp - learning and contribution experience with ❤️ and 🤗 from the thumbor team

Thumbor-bootcamp - learning and contribution experience with ❤️ and ?? from the thumbor team

Thumbor (by @globocom) 9 Jul 11, 2022
Todos os exercícios do Curso de Python, do canal Curso em Vídeo, resolvidos em Python, Javascript, Java, C++, C# e mais...

Exercícios - CeV Oferecido por Linguagens utilizadas atualmente O que vai encontrar aqui? ?? Esse repositório é dedicado a armazenar todos os enunciad

Coding in Community 43 Nov 10, 2022