我有一个 python 脚本,它在它正在运行的环境中引起了一些问题。有人告诉我它“不会释放它打开以读取数据的文件管道”。我相信问题出在最后一行。我想确保我做出正确的改变。这是在 Python 2.7 环境中运行谢谢。
#!/usr/bin/env python
import subprocess
import urllib
from xml.dom import minidom
ZIPCODE = '06840'
TEMP_TYPE = 'f'
HVAC_ZONES = ['HVAC']
TSTAT = 5
WEATHER_URL = 'http://xml.weather.yahoo.com/forecastrss?p=' + ZIPCODE +'&u=' + TEMP_TYPE
WEATHER_NS = 'http://xml.weather.yahoo.com/ns/rss/1.0'
dom = minidom.parse(urllib.urlopen(WEATHER_URL))
ycondition = dom.getElementsByTagNameNS(WEATHER_NS, 'condition')[0]
CURRENT_OUTDOOR_TEMP = ycondition.getAttribute('temp')
for zone in HVAC_ZONES:
i =0
while i < TSTAT:
i += 1
subprocess.Popen(['/Users/RPM/Applications/RacePointMedia/sclibridge','writestate', zone + '.HVAC_controller.ThermostatCurrentRemoteTemperature'+ '_' + str(i),CURRENT_OUTDOOR_TEMP + TEMP_TYPE.upper()], stdin=subprocess.PIPE)
我知道我需要添加一个关闭但不想确保我没有任何其他内存泄漏。我需要添加吗
subprocess.close
这会是使用 subprocess.call 的更好方法吗?你需要释放/关闭 subprocess.call() 吗?
#!/usr/bin/env python
import subprocess
import urllib
from xml.dom import minidom
ZIPCODE = '06457'
TEMP_TYPE = 'f' # f - farhenheit c- celsius (case sensative)
HVAC_ZONES = ['HVAC', 'HVAC2']
TSTAT = 64
WEATHER_URL = 'http://xml.weather.yahoo.com/forecastrss?p=' + ZIPCODE +'&u=' + TEMP_TYPE
WEATHER_NS = 'http://xml.weather.yahoo.com/ns/rss/1.0'
dom = minidom.parse(urllib.urlopen(WEATHER_URL))
ycondition = dom.getElementsByTagNameNS(WEATHER_NS, 'condition')[0]
CURRENT_OUTDOOR_TEMP = ycondition.getAttribute('temp')
print(CURRENT_OUTDOOR_TEMP)
for zone in HVAC_ZONES:
i =0
while i < TSTAT:
i += 1
command = ['/Users/RPM/Applications/RacePointMedia/sclibridge','writestate', zone + '.HVAC_controller.ThermostatCurrentRemoteTemperature'+ '_' + str(i),CURRENT_OUTDOOR_TEMP + TEMP_TYPE]
subprocess.call(str(command),shell=True)
编辑
好的,我已经用建议重写了这个,但是我仍然需要 shell=True 见下文
#!/usr/bin/env python
#define imports
import sys
import subprocess
import os
from subprocess import STDOUT
DEVNULL = open(os.devnull, "r+b")
#start global definitions
command = ['/Users/RPM/Applications/RacePointMedia/sclibridge servicerequest "Wine Cellar" "" "" "1" "" "Pause"']
#start main program
subprocess.call(command, close_fds=True, stdin=DEVNULL, stdout=DEVNULL, stderr=STDOUT,shell=True)
我在没有 shell=True 的情况下尝试过,但出现以下错误,我主要担心的是内存泄漏。
File "./test.py", line 14, in <module>
subprocess.call(commamd,close_fds=True)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 493, in call
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 679, in __init__
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1228, in _execute_child