Gravity Mass
Gravity Mass

Reputation: 605

How to save output of subprocess.run into a string?

There is a git command that I am using

git log --format=%H 3c2232a5583711aa5f37d0f21014934f67913202

Here the long string at the end is the commit id. This command gives the list of previously commit ids of the branch. The output is like,

3c2232a5583711aa5f37d0f21014934f67913202
9i45e2a5583711aa5f37d0f21014934f679132de

I am trying to issue the same command in python and trying to store the output in a string as the following,

import subprocess

result = subprocess.run(
    [
        "cd",
        "/Users/XYZ/Desktop/gitrepo",
        "git",
        "log",
        "3c2232a5583711aa5f37d0f21014934f67913202",
    ],
    stdout=subprocess.PIPE,
    stderr=subprocess.STDOUT,
)
print(result.stdout.decode("utf-8"), type(result.stdout.decode("utf-8")))

But the output of the print is empty! I tried subprocess.run with ["-ls", "-l"] and it worked well. The git command works on command line but I am not able to capture it in a string. When I print the result alone,

CompletedProcess(args=['cd', '/Users/XYZ/Desktop/gitrepo', 'git', 'log', '3c2232a5583711aa5f37d0f21014934f67913202'], returncode=0, stdout=b'')

How can I save the git command's output in a string? I am issuing two commands in one line. Should I issue the commands separately? If I should then, how can I (a) navigate to git folder and (b) issue git command there?

Upvotes: 2

Views: 5863

Answers (1)

cg909
cg909

Reputation: 2556

Your code runs cd "/Users/XYZ/Desktop/gitrepo" "git" "log" "3c2232a5583711aa5f37d0f21014934f67913202" which is probably not what you intended.

The best way is not to interpret changing the working directory as a separate command but as part of the setup of the environment to run the git command. The subprocess module has the keyword argument cwd for that.

If cwd is not None, the function changes the working directory to cwd before executing the child. In particular, the function looks for executable (or for the first item in args) relative to cwd if the executable path is a relative path.

This is only documented for the Popen constructor but the subprocess.run documentation has this paragraph:

The arguments shown above are merely the most common ones, described below in Frequently Used Arguments (hence the use of keyword-only notation in the abbreviated signature). The full function signature is largely the same as that of the Popen constructor - apart from timeout, input and check, all the arguments to this function are passed through to that interface.

So you can rewrite your code like this:

import subprocess

result = subprocess.run(
    [
        "git",
        "log",
        "3c2232a5583711aa5f37d0f21014934f67913202",
    ],
    cwd="/Users/XYZ/Desktop/gitrepo"
    stdout=subprocess.PIPE,
    stderr=subprocess.STDOUT,
)
print(result.stdout.decode("utf-8"), type(result.stdout.decode("utf-8")))

Upvotes: 4

Related Questions