how do I commit and push to github from python shell?
Asked Answered
C

3

7

I have three .py files saved in the python shell/IDLE. I would like to commit and push them to my GitHub account/repo. Is this possible? and if so how?

Coercion answered 9/10, 2015 at 14:18 Comment(3)
No. You have to do this from a command line/GUI git client.Improper
@MorganThrapp not true, you could use a library like GitPythonIsallobar
It's worth mentioning, as the documentation states, that using shell=True in subprocess.call() is not completely safe, as it can lead to shell injection.Gingerich
S
5

To do it from macOS (Mac terminal) using the shell from python, you can do this:

#Import dependencies
from subprocess import call

#Commit Message
commit_message = "Adding sample files"

#Stage the file 
call('git add .', shell = True)

# Add your commit
call('git commit -m "'+ commit_message +'"', shell = True)

#Push the new or update files
call('git push origin master', shell = True)
Spirituality answered 8/3, 2018 at 12:40 Comment(0)
K
4

There's a python library for git in python called GitPython. Another way to this is doing it from shell(if you're using linux). For Example:

from subprocess import call
call('git add .', shell = True)
call('git commit -a "commiting..."', shell = True)
call('git push origin master', shell = True)
Kragh answered 9/10, 2015 at 14:49 Comment(2)
how to we set the path?Apfelstadt
Not sure if I understand your question, which path?Kragh
S
3

You can execute arbitrary shell commands using the subprocess module.

Setting up a test folder to play with:

$ cd ~/test
$ touch README.md
$ ipython

Working with git from IPython:

In [1]: import subprocess

In [2]: print subprocess.check_output('git init', shell=True)

Initialized empty Git repository in /home/parelio/test/.git/

In [3]: print subprocess.check_output('git add .', shell=True)

In [4]: print subprocess.check_output('git commit -m "a commit"', shell=True)

[master (root-commit) 16b6499] Initial commit
 1 file changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 README.md

A note on shell=True:

Don't use shell=True when you are working with untrusted user input. See the warning in the Python docs.

One more note:

As with many things in programming - just because you can doesn't mean that you should. My personal preference in a situation like this would be to use an existing library rather than roll my own.

Sphene answered 9/10, 2015 at 14:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.