0

I have a Python code that will run a script file.The script file will output the version tag of specific git repository.

My script file named 'start.sh' is as follows:

#!/bin/sh
git clone https://xxxxxxxxxx:x-oauth-basic@github.com/xxxxxxx/xxxxx.git
cd xxxxxxxx
git config --global user.email "xxxxxxxx"
git config --global user.name "xxxxxxxxx"
IMAGE_TAG=`echo \`git describe --tags\``
echo $IMAGE_TAG

My Python code is as follows:

import os
git_tag = os.popen('sh start.sh')
print(git_tag)

When I run the script file separately, it will return me the git tag. But, Whenever I try to print it in the Python code, it's not working.

How can I solve this issue?

halfer
  • 19,824
  • 17
  • 99
  • 186
Deependra Dangal
  • 1,145
  • 1
  • 13
  • 36
  • 1
    You should use `subprocess` instead see [here](https://stackoverflow.com/questions/2502833/store-output-of-subprocess-popen-call-in-a-string). – Paul Rooney Sep 25 '20 at 05:54
  • What's with the nested [useless `echo`s?](http://www.iki.fi/era/unix/award.html#echo) – tripleee Sep 25 '20 at 06:47

4 Answers4

1

Since you are using Python anyway, you could think of using GitPython as an alternative. You can list all your tags with:

from git import Repo
repo = Repo("path/to/repo")
print(repo.tags)
speedi33
  • 136
  • 1
  • 7
  • I have private git hub repository. So, it seems like I need to add authentication mechanism with this library as well. – Deependra Dangal Sep 25 '20 at 06:57
  • Maybe have a look at https://stackoverflow.com/a/62796479/8505949. I haven't verified it myself but seems to be a good point to start from. – speedi33 Sep 25 '20 at 07:11
1

Try like this

from subprocess import check_output
out = check_output(['sh', 'start.sh'])
print(out)
tripleee
  • 175,061
  • 34
  • 275
  • 318
Ivan
  • 6,188
  • 1
  • 16
  • 23
0

According to python's documentation, os.popen() function has been deprecated since version 2.6. You might want to use subprocess module.

P.S: I wanted to comment but couldn't hence this answer.

  • You are linking to Python 2 documentation. It was reinstated sometime in Python 3.x, though now it's simply an (unnecessary) wrapper for `subprocess`. – tripleee Sep 25 '20 at 06:49
0

For python3-X:

from subprocess
git_tag = subprocess.run(['sh', 'start.sh'], capture_output=True, text=True)
print(git_tag.stdout)
User123
  • 1,498
  • 2
  • 12
  • 26