Partially Attended

an irregularly updated blog by Ian Mulvany

python - running commands from within a directory

Thu Apr 19, 2018

77 Words

A neat python snippet for jumping into a directory, running a script, and jumping out again, found on Stackoverflow, provided by Brian Hunt.

from subprocess import Popen, PIPE
import os
import sys

class cd:
  """Context manager for changing the current working directory
  see https://stackoverflow.com/questions/431684/how-do-i-cd-in-python
  """
  def __init__(self, newPath):
    self.newPath = os.path.expanduser(newPath)

  def __enter__(self):
  self.savedPath = os.getcwd()
    os.chdir(self.newPath)

  def __exit__(self, etype, value, traceback):
    os.chdir(self.savedPath)

with cd("~/blog/partiallyattended"):
  title = new_post.title
  process = subprocess.call(["git", "commit", "-m","`new post: `"+title], \
  stdout=subprocess.PIPE)
This work is licensed under a Creative Commons Attribution 4.0 International License