【问题标题】:how do I commit and push to github from python shell?如何从 python shell 提交并推送到 github?
【发布时间】:2015-10-09 14:18:50
【问题描述】:

我在 python shell/IDLE 中保存了三个 .py 文件。我想提交并将它们推送到我的 GitHub 帐户/存储库。这可能吗?如果是的话怎么办?

【问题讨论】:

  • 没有。您必须从命令行/GUI git 客户端执行此操作。
  • @MorganThrapp 不正确,您可以使用像 GitPython 这样的库
  • 值得一提的是,正如documentation 所述,在subprocess.call() 中使用shell=True 并不完全安全,因为它可能导致shell injection

标签: python github python-idle


【解决方案1】:

要从 macOS(Mac 终端)使用 python 的 shell 执行此操作,您可以这样做:

#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)

【讨论】:

    【解决方案2】:

    python 中有一个用于 git 的 python 库,名为 GitPython。 另一种方法是从 shell 中进行(如果您使用的是 linux)。 例如:

    from subprocess import call
    call('git add .', shell = True)
    call('git commit -a "commiting..."', shell = True)
    call('git push origin master', shell = True)
    

    【讨论】:

    • 我们如何设置路径?
    • 不确定我是否理解您的问题,哪条路径?
    【解决方案3】:

    您可以使用subprocess 模块执行任意shell 命令。

    设置一个测试文件夹来玩:

    $ cd ~/test
    $ touch README.md
    $ 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
    

    关于shell=True的注释:

    当您使用不受信任的用户输入时,不要使用shell=True。请参阅warning in the Python docs

    还有一点说明:

    与编程中的许多事情一样 - 仅仅因为您可以并不意味着您应该这样做。在这种情况下,我个人的偏好是使用现有的库而不是我自己的。

    【讨论】:

      猜你喜欢
      • 2021-10-08
      • 2020-01-04
      • 1970-01-01
      • 2023-04-09
      • 2021-06-23
      • 1970-01-01
      • 1970-01-01
      • 2012-08-01
      相关资源
      最近更新 更多