使用 Python 设置 Windows 系统变量

Setting Up Windows System Variables with Python

我希望通过 python 设置两个独立的系统变量,以便 gdal_calc 和 gdal_translate 都能在我的计算机上正常工作。但是,我附加的路径和我添加的变量似乎无法正常工作。有什么建议吗?

#!/usr/bin/env python

import subprocess
from subprocess import call
import sys
import os


# make dictionary of environmental variables to set up for gdal_calc and gdal_translate

gdal_env = os.environ.copy()

# modify and add variables for environment so that GDAL runs properly

gdal_env["GDAL_DATA"] = "C:\Program Files (x86)\GDAL\gdal-data"
gdal_env["GDAL_DRIVER_PATH"] = "C:\Program Files (x86)\GDAL\gdalplugins"
gdal_env["PATH"] = gdal_env["PATH"] + ";C:\Program Files (x86)\GDAL\bin"

# Set constants
# The pathway to the images files are nested within the '--outfile=' command

inHVFile = os.path.expanduser('~\Desktop\Components\Float32\newHV32.img')
outPlacement = os.path.expanduser('~\Desktop\Components\Zeros\newHVZeros_1.img')
outVFile = '--outfile=' + outPlacement
#calc_cmd_HV = ['gdal_calc.py', '-A', inHVFile, outVFile, '--calc=A+1']

inVHFile = os.path.expanduser('~\Desktop\Components\Float32\newVH32.img')
outPlacement_1 = os.path.expanduser('~\Desktop\Components\Zeros\newVHZeros_1.img')
outVFile_1 = '--outfile=' + outPlacement_1
#calc_cmd_VH = ['gdal_calc.py', '-A', inVHFile, outVFile_1, '--calc=A+1']


subprocess.call([sys.executable,'C:\Program Files (x86)\GDAL\gdal_calc.py', inHVFile, outVFile, '--calc=A+1'], env=gdal_env)
subprocess.call([sys.executable,'C:\Program Files (x86)\GDAL\gdal_calc.py', inVHFile, outVFile_1, '--calc=A+1'], env=gdal_env)
#subprocess.call([sys.executable, 'C:\Program Files (x86)\GDAL\gdal_calc.py','-A', inHVFile, outVFile, '--calc=A+1'])

#subprocess.call([sys.executable, 'C:\Program Files (x86)\GDAL\gdal_calc.py','-A', inVHFile, outVFile_1, '--calc=A+1'])

环境变量保存有关在哪里可以找到文件和程序的信息。当使用 Python 通过 subprocess.callsubprocess.Popen 调用命令行程序时,您可以在生成子进程时指定一组环境变量。这是通过将字典传递给 callPopenenv kwarg 来完成的。如果未指定env,将使用默认环境变量。

在 Python 会话结束后,对 os.environ 中存储的环境变量的修改将不会保留。

要通过 subprocess.call 调用 GDAL 程序,请执行以下操作:

import os
import subprocess
import sys

# make dictionary of environmental variables
gdal_env = os.environ.copy()

# modify and add variables
gdal_env["GDAL_DATA"] = "C:\Program Files (x86)\GDAL\gdal-data"
gdal_env["GDAL_DRIVER_PATH"] = "C:\Program Files (x86)\GDAL\gdalplugins"
gdal_env["PATH"] = gdal_env["PATH"] + ";C:\Program Files (x86)\GDAL\bin"


# ... do preparation ...
a = "a.tif"
b = "b.tif"
output = "output.tif"

calc_cmd = [sys.executable, 'gdal_calc.py', '-A', a, '-B', b, '--outfile='+output, '--calc=A+B']

# spawn a new subprocess
subprocess.call(calc_cmd, env=gdal_env)