简体   繁体   English

在 python 中执行 git 命令并配置凭证

[英]Execute git commands in python and configure credentials

I am working on some script where in I generate a CSV file and I need to upload that file to a repository using python script.我正在处理一些脚本,其中我生成了一个 CSV 文件,我需要使用 python 脚本将该文件上传到存储库。

Here is how I have files in my linux directory now这是我现在在 linux 目录中拥有文件的方式

Project_Repo_Details.csv -> file
repo1-> Directory
script1.py
script2.py

so repo1 is my folder created when I cloned my repository in linux.所以 repo1 是我在 linux 中克隆存储库时创建的文件夹。 Now I need to write script to move my csv file to that repo and need to execute below commands.现在我需要编写脚本来将我的 csv 文件移动到该 repo 并需要执行以下命令。

git add .
git commit -m "adding file"
git push origin master

Also one more problem is while executing this commands it asks for credentials also.还有一个问题是在执行此命令时它也要求提供凭据。 I tried to use subprocess like below:我尝试使用如下子流程:

import subprocess
import os

def movefileAndPush():
    os.rename('Project_Repo_Details.csv','repo1/Project_Repo_Details.csv')
    
    subprocess.Popen("cd repo1")
    subprocess.Popen("git add Project_Repo_Details.csv")
    subprocess.Popen("git commit -m PCV-99 adding repo report")
    subprocess.Popen("git push origin master")

This script just ran and nothing happened.这个脚本刚刚运行,什么也没发生。 Please help me in completing this script.请帮助我完成这个脚本。

I solved my problem.我解决了我的问题。 I used os.chdir() to point things to a specific directory and subprocess.run to execute commands and I passed username and password in git push command.我使用 os.chdir() 将内容指向特定目录并使用 subprocess.run 执行命令,并在 git 推送命令中传递用户名和密码。 It worked awesome:)效果很棒:)

import subprocess
import os

def movefileAndPush():
    try:
        x = subprocess.run(['cp','Project_Repo_Details.csv','bitbucket_repo_report/Project_Repo_Details.csv'])
        print(x.stdout)
        print(x.stderr)
        os.chdir("/dirs/Repo-report_scripts/bitbucket_repo_report")
        subprocess.run(['git','config','--global','user.email','test@gmail.com'])
        subprocess.run(['git','add','Project_Repo_Details.csv'])
        subprocess.run(['git','commit','-m','PQR-99 adding repo report'])
        subprocess.run(['git','push','https://username:password@gitreporul','--all'])
    except Exception as e:
        print("Error occured :".format(e))
if __name__ == '__main__':
   movefileAndPush()

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

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