class Chdir:
""" change in and out of dir """
def __init__(self, newPath):
self.newPath = newPath
def __enter__(self):
self.savedPath = os.getcwd()
os.chdir(self.newPath)
def __exit__(self, etype, value, traceback):
os.chdir(self.savedPath)
使用上面的,
ROOT = "/home/username/my-blog/blogname/"
with Chdir(ROOT):
print os.path.exists(os.getcwd()+'/.git')
print os.path.exists(os.getcwd()+'/notes/')
subprocess.Popen(['git', 'add', '--ignore-removal', 'notes/'])
输出:
True
True
fatal: Not a git repository (or any of the parent directories): .git
从print语句测试中,很明显还存在git repository exists
和后续的notes文件夹。但是代码仍然失败
修改 用于测试的Shell脚本
1 echo "Testing ...."
2 cd /home/username/my-blog/blogname/
3 git add --ignore-removal notes/
4 git add --ignore-removal data.json
5 git status
on source test.sh
我得到了通常的模糊
Testing ....
On branch master
Your branch is ahead of 'origin/master' by 1 commit.
(use "git push" to publish your local commits)
.... etc
完整来源
class Git:
def __init__(self, message="GitNote Commit"):
self.message = message
def __enter__(self):
with Chdir(ROOT):
print os.path.exists(os.getcwd()+'/.git')
print os.path.exists(os.getcwd()+'/notes/')
subprocess.Popen(['git', 'add', '--ignore-removal', 'notes/'], cwd=ROOT)
subprocess.Popen(['git', 'add', '--ignore-removal', 'data.json'], cwd=ROOT)
subprocess.Popen(['git', 'add', '--ignore-removal', 'images/'], cwd=ROOT)
return self
def __iter__(self):
with Chdir(ROOT):
changed_files = subprocess.check_output(['git','diff',
'--name-only','HEAD']).split('\n')[:-1]
relevant_changes = [f for f in changed_files if f[-3:]=='.md'
and os.path.isfile(ROOT+f)]
for item in relevant_changes:
yield item
def __exit__(self,exc_type, exc_value, traceback):
if exc_type is not None:
print exc_type, exc_value, traceback
subprocess.Popen(['git', '--no-pager', 'commit', '-m', self.message])
答案 0 :(得分:1)
请尝试设置cwd
kwarg of Popen
。
如,
subprocess.Popen(['git', 'add', '--ignore-removal', 'notes/'], cwd=ROOT)