Skip to content

Instantly share code, notes, and snippets.

@GaryLee
Last active October 3, 2017 01:44
Show Gist options
  • Save GaryLee/4706203957e13cc9e58c27e4122a5749 to your computer and use it in GitHub Desktop.
Save GaryLee/4706203957e13cc9e58c27e4122a5749 to your computer and use it in GitHub Desktop.
Execute shell command or print text in Perl-like manner.
import sys
import os
from subprocess import CalledProcessError, check_output
def cmd(cmd_arg, local_only=False):
"""Execute shell command in Perl-like manner."""
if local_only:
ctx = sys._getframe(1).f_locals
else:
ctx = globals().copy()
ctx.update(sys._getframe(1).f_locals)
for ln in check_output(cmd_arg.format(**ctx), shell=True).split(os.linesep):
yield ln
def fmt(spec):
"""Format string with caller's variable scope."""
return spec.format(**sys._getframe(1).f_locals)
def fmt2(spec):
"""Format string with caller's variable scope and global scope."""
ctx = globals().copy()
ctx.update(sys._getframe(1).f_locals)
return spec.format(**ctx)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment