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?

3
  • No. You have to do this from a command line/GUI git client. Commented Oct 9, 2015 at 14:19
  • 4
    @MorganThrapp not true, you could use a library like GitPython Commented Oct 9, 2015 at 14:21
  • 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. Commented Feb 3, 2017 at 14:17

3 Answers 3

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)
Sign up to request clarification or add additional context in comments.

Comments

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)

2 Comments

how to we set the path?
Not sure if I understand your question, which path?
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.