简体   繁体   中英

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

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?

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)

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM