简体   繁体   中英

Cant Git Push Using Python (Subprocess)?

I have this script that is supposed to push the files in the script's current directory to a repo:

def pushToGit():
    currDir = os.path.dirname(os.path.realpath(sys.argv[0]))
    try:
        shutil.rmtree(os.path.join(currDir, '.git'))
    except:
        pass
    try:
        cp = cmd.run("git init", check=True, shell=True, cwd=currDir)
        cp = cmd.run(f"git remote add origin git@github.com:johnsmith/repo_hold.git", check=True, shell=True, cwd=currDir + "//")
        cp = cmd.run("git config user.name 'john smith'", check=True, shell=True, cwd=currDir + "//")
        cp = cmd.run("git config user.email 'john@smith.com'", check=True, shell=True, cwd=currDir + "//")
        cp = cmd.run("git add .", check=True, shell=True, cwd=currDir + "//")
        message = f"Some generated message here"
        cp = cmd.run(f"git commit -m '{message}'", check=True, shell=True, cwd=currDir + "//")
        cp = cmd.run("git push -u origin master", check=True, shell=True, cwd=currDir + "//")
        return True
    except Exception as e:
        return False

The process is simple: just initialize the folder, add the configuration, add the files, commit with a message, and push.

In this example, I am trying to use the SSH method since this will be ran automatically, so it cannot type a password. The SSH keys are in the same folder (for the sake of example) and are attached to my GitHub account.

However, I run into the following error:

* Running on http://127.0.0.1:2897/ (Press CTRL+C to quit)
Initialized empty Git repository in C:/Users/John/Desktop/my_repo/.git/
warning: LF will be replaced by CRLF in id_rsa.
The file will have its original line endings in your working directory
error: pathspec 'URL' did not match any file(s) known to git
error: pathspec 'added'' did not match any file(s) known to git
127.0.0.1 - - [08/Sep/2020 22:13:36] "←[37mGET /<url post request here> HTTP/1.1←[0m" 200 -

I am not sure what is causing the problem. I don't understand the error in the console. This is the first time I'm using the SSH method but I don't see how I would be using it wrong.

If it helps, this is what the files look like in the directory:

目录视图

What am I doing wrong?

First, add some echo between your command to isolate the one which trigger the error.

Second, add a git status to check:

  • if you are in the right working directory
  • the state of the files

An error like pathspec 'added'' did not match any file(s) known to git seems to indicate it is trying to add or commit files using the output of a previous command.

Using gitpython-developers/GitPython would be safer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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