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?
how do I commit and push to github from python shell?
Asked Answered
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)
how to we set the path? –
Apfelstadt
Not sure if I understand your question, which path? –
Kragh
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.
© 2022 - 2024 — McMap. All rights reserved.
shell=True
insubprocess.call()
is not completely safe, as it can lead to shell injection. – Gingerich