0

I would like to execute the following Windows 7 commands from Python:

SET PATH=%PATH%;C:\Qt\Qt5.5.1\5.5\mingw492_32\bin;C:\Qt\Qt5.5.1\Tools\mingw492_32\bin

C:\Qt\Qt5.5.1\5.5\mingw492_32\bin\qmake untitled5.pro
C:\Qt\Qt5.5.1\Tools\mingw492_32\bin\mingw32-make
C:\Qt\Qt5.5.1\Tools\mingw492_32\bin\mingw32-make clean

I tried:

os.system("SET PATH=%PATH%;C:\\Qt\\Qt5.5.1\\5.5\\mingw492_32\\bin;C:\\Qt\\Qt5.5.1\\Tools\\mingw492_32\\bin")
os.system("qmake untitled5.pro")
os.system("mingw32-make.exe")
os.system("mingw32-make clean")

But got:

'qmake' is not recognized as an internal or external command,
operable program or batch file.

'mingw32-make.exe' is not recognized as an internal or external command,
operable program or batch file.

'mingw32-make' is not recognized as an internal or external command,
operable program or batch file.

It seems the PATH doesn't get changed. Would some one give an idea?

if I put these commands in cmd.bat and then call os.system("cmd.bat") it works. But I'll prefer not to create this additional file (cmd.bat).

KcFnMi
  • 5,516
  • 10
  • 62
  • 136
  • Create an instance of the [`subprocess.Popen`](https://docs.python.org/2/library/subprocess.html?highlight=popen#subprocess.Popen) class and pass it the environment you want via the `env` keyword argument. – martineau Feb 29 '16 at 01:25
  • Why do you need to use python at all? – OneCricketeer Feb 29 '16 at 01:25
  • I'm planning to call the Python script from Jenkins. Until now I was going with Bash and/or Bat scripts. – KcFnMi Feb 29 '16 at 02:25

2 Answers2

0

The environment variables only persist in processes and child processes. What you're doing is spawning a subprocess, setting the path environment variable and then exiting that process, losing it's environment.

Putting everything in a batch file is one way of solving this. You could also use subprocess to spawn a command shell and then pipe your commands via stdin.

See: How do I write to a Python subprocess' stdin?

Community
  • 1
  • 1
Jesse Weigert
  • 4,714
  • 5
  • 28
  • 37
0

Many of the commands in subprocess let you pass an environment to use for the child process. You can copy your environment, change what you want and then exec the command. You can even create the environment from scratch so that nothing that happens to be in your current environment messes up what you are calling. Here's an example

import os
import subprocess as subp

environ = os.environ.copy()
environ['PATH'] = os.pathsep.join(environ['PATH'], 
    ["C:\\Qt\\Qt5.5.1\\5.5\\mingw492_32\\bin",
    "C:\\Qt\\Qt5.5.1\\Tools\\mingw492_32\\bin"])

subp.call(["qmake", "untitled5.pro", env=environ)
subp.call(["mingw32-make.exe"], env=environ)
subp.call(["mingw32-make", "clean"], env=environ)
tdelaney
  • 73,364
  • 6
  • 83
  • 116