MagSec
MagSec

Reputation: 346

Python: run a python script inside the git-bash environment

I having problems to run a python script inside the git-bash environment. My app is running (for now) from an exe-container (py2exe) and it should just execute another python script, but inside the git-bash environment.

The app and the git-bash.exe are inside the same directory (the entire portable version of git is extracted into this folder). The second script I want to run is in a subfolder named scripts.

Here the python file, which will be compiled as the self executable: import os

try:
    root = os.path.dirname(__file__)
except: 
    root = os.path.dirname(sys.argv[0])

git       = os.path.join(root,"git-bash.exe")
gitScript = os.path.join(root,"scripts","git_deploy.py")

I was trying different variations, but without any success:

# 1st try:
subprocess.Popen(["python", gitScript], executable=git)

# 2nd try:
subprocess.Popen(["python %s"%gitScript], shell=True, executable=git)

# 3rd try:
subprocess.Popen(["-c", "python", gitScript], executable=git)

# 4th try:
subprocess.Popen([git, "python", gitScript])

# 5th try:
subprocess.Popen([git, "-c", "python", gitScript])

Any idea what I doing wrong here?

Thanks

Upvotes: 1

Views: 4541

Answers (1)

Joe Young
Joe Young

Reputation: 5885

I've given the following a quick test and it seems to work. A couple of things:

  • You have to ensure C:\Program Files (x86)\Git\bin is in your System's PATH environment variable
  • You'll have to fix the paths yourself to match your system's configuration.
  • Any slashes in paths need to be escape (i.e. "double slashes").
  • The path to your git_deploy.py will need to be wrapped in double quotes, which means you'll have to escape those quotes with a double back-slash: \\"<path_to_git_deploy.py>\\"

The example code:

import os, shlex, subprocess
from subprocess import Popen, PIPE, STDOUT

gitScript = 'C:\\Users\\MYUSERNAME\\Downloads\\scripts\\git_deploy.py'
command = '"C:\\Program Files (x86)\\Git\\bin\\sh.exe" --login -i -c "python \\"' + gitScript + '\\""'
command_args = shlex.split(command)
process = Popen(command_args, stdout=PIPE, stderr=STDOUT)
output, err = process.communicate()
print output

Upvotes: 1

Related Questions