views:

226

answers:

2

I'm writing a python program that needs to set the environment CFLAGS as needed.

I'm using the subprocess module to perform some operations, but, I'm not sure this is the correct way of doing this.

The script will first set the CFLAGS and then compile some code, so the cflags need to stay put while the code is compiled.

I know there is the os.environ['CXXFLAGS'] which defaults to "" in my system. So my question is, do I just need to set the os.environ['CXXFLAGS'] value before compiling the code, or do I need to do it some other way?

Please advise

+1  A: 

You can do this without modifying the python process's environment.

# Make a copy of the environment and modify that.
myenv = dict(os.environ)
myenv["CXXFLAGS"] = "-DFOO"

# Pass the modified environment to the subprocess.
subprocess.check_call(["make", "install"], env=myenv)

See the documentation for Python's subprocess module.

Jason Orendorff
What about the simply modifying `os.environ['CXXFLAGS']`? If I do it in this sequence` os.environ['CXXFLAGS'] = "-O2 -march=i586 -mtune=i686" subprocess.Popen(['./configure', '--prefix=/usr'], stdout=subprocess.PIPE, stderr = subrprocess.STDOUT) subprocess.Popen('make', stdout=subprocess.PIPE, stderr = subrprocess.STDOUT)`Will that work?
M0E-lnx
That should work fine.
Jason Orendorff
A: 

Setting it in the environment by modifying os.environ['CXXFLAGS'] should work. However, the way I've always passed extra CXXFLAGS to ./configure is by passing it on the command line, e.g.:

cmd = [
    './configure',
    'CXXFLAGS=-O2 -march=i586 -mtune=i686',
]
subprocess.Popen(cmd)

When done this way, you shouldn't need to set CXXFLAGS in the environment or explicitly pass it to make (autotools will create the Makefiles so that they include your custom CXXFLAGS).

Zach Hirsch
This is how I'm used to doing it, but this is my first time doing it from python, and my problem is that when I do it like this, configure fails, and it says '-march' is not a valid option to configure.
M0E-lnx
You probably have some quoting issue. Try using the shell=False argument (the default) to subprocess.Popen and passing the arguments like I did above.
Zach Hirsch