使用Python设置Windows系统变量

时间:2016-11-01 12:57:33

标签: operating-system gdal sys

我希望通过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'])

1 个答案:

答案 0 :(得分:1)

环境变量包含有关可以找到文件和程序的位置的信息。使用Python通过subprocess.callsubprocess.Popen调用命令行程序时,可以在生成子进程时指定一组环境变量。这是通过将字典传递给envcall的{​​{1}} kwarg来完成的。如果未指定Popen,则将使用默认环境变量。

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

要通过os.environ致电GDAL计划,请执行以下操作:

subprocess.call