简体   繁体   English

我如何从python shell提交并推送到github?

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

I have three .py files saved in the python shell/IDLE. 我在python shell / IDLE中保存了三个.py文件。 I would like to commit and push them to my GitHub account/repo. 我想承诺并将它们推送到我的GitHub帐户/回购。 Is this possible? 这可能吗? and if so how? 如果是这样怎么样?

To do it from macOS (Mac terminal) using the shell from python, you can do this: 要使用python中的shell从macOS(Mac终端)执行此操作,您可以执行以下操作:

#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 . 在python中有一个名为GitPython的 git python库。 Another way to this is doing it from shell(if you're using linux). 另一种方法是从shell(如果你使用的是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. 您可以使用subprocess模块执行任意shell命令。

Setting up a test folder to play with: 设置要使用的测试文件夹:

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

Working with git from IPython: 使用来自IPython的git:

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 : 关于shell=True的注释shell=True

Don't use shell=True when you are working with untrusted user input. 使用不受信任的用户输入时,请勿使用shell=True See the warning in the Python docs . 请参阅Python文档中警告

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. 在这种情况下,我个人的偏好是使用现有的库而不是自己的库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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