logoalt Hacker News

rjmilllast Friday at 3:36 PM3 repliesview on HN

Odd, I don't see any mention of subprocess.run, the workhorse of python scripting.

Quick rundown for the unfamiliar:

Give it a command as a list of strings (e.g., subprocess.run(["echo", "foo"]).)

It takes a bunch of flags, but the most useful (but not immediately obvious) ones are:

  check=True: Raise an error if the command fails
  capture_output=True: Captures stdout/stderr on the CompletedProcess
  text=True: Automatically convert the stdout/stderr bytes to strings
By default, subprocess.run will print the stdout/stderr to the script's output (like bash, basically), so I only bother with capture_output if I need information in the output for a later step.

Replies

bccdeeyesterday at 3:42 AM

Also `asyncio.subprocess`, which lets you manage multiple concurrently running commands. Very handy if you need to orchestrate several commands together.

theomegayesterday at 8:46 PM

One thing I can recommend that makes scripting in python with external commands a lot easier is the `sh` module:

https://pypi.org/project/sh/

Basically you can just `from sh import [command]` and then have an installed binary command available as function

  from sh import ifconfig
  print(ifconfig("eth0"))
show 7 replies
albertzeyeryesterday at 9:13 PM

I think the point is that for most things, you don't need to call any external tools. Python's standard library comes already with lots of features, and there are many packages you can install.