Skip to content

Commit 63be9e0

Browse files
committed
remove memory leaks w/open().write(); while at it clean up warnings shown by spyder
1 parent 0f89a97 commit 63be9e0

File tree

9 files changed

+74
-40
lines changed

9 files changed

+74
-40
lines changed

GSASII/GSASIIdataGUI.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -457,6 +457,7 @@ def ShowVersions():
457457
if GSASIIpath.HowIsG2Installed().startswith('git'):
458458
try:
459459
import git
460+
git
460461
except ImportError as msg:
461462
if 'Failed to initialize' in msg.msg:
462463
print('The gitpython package is unable to locate a git installation.')
@@ -473,6 +474,7 @@ def ShowVersions():
473474
# warn if problems with requests package
474475
try:
475476
import requests
477+
requests
476478
except:
477479
print('Warning: Python requests package not installed (required for\n'+
478480
' GSAS-II to access web pages or self-install binary modules)')
@@ -639,6 +641,7 @@ def _Add_FileMenuItems(self, parent):
639641
if GSASIIpath.GetConfigValue('debug'):
640642
try:
641643
import IPython
644+
IPython
642645
item = parent.Append(wx.ID_ANY,"IPython Console",'')
643646
self.Bind(wx.EVT_MENU,
644647
lambda event:GSASIIpath.IPyBreak(),
@@ -5743,6 +5746,7 @@ def OnClusterAnalysis(self,event):
57435746
try:
57445747
SKLearn = False
57455748
import sklearn.cluster
5749+
sklearn.cluster
57465750
SKLearn = True
57475751
except:
57485752
res = GSASIIpath.condaInstall('scikit-learn')
@@ -7410,7 +7414,8 @@ def OnAddNotebook(event):
74107414
def OnSaveNotebook(event):
74117415
filename = os.path.splitext(G2frame.GSASprojectfile)[0]+'_notebook.txt'
74127416
filename = os.path.join(G2frame.dirname,filename)
7413-
open(filename,'w').write(textBox.GetText())
7417+
with open(filename,'w') as fp:
7418+
fp.write(textBox.GetText())
74147419
print(f'Notebook contents written into {filename}')
74157420
def onPlotNotebook():
74167421
'Locate R values from the Notebook and plot them'

GSASII/GSASIIpath.py

Lines changed: 31 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
import sys
1010
import platform
1111
import glob
12-
import pathlib
12+
#import pathlib
1313
import subprocess
1414
import datetime as dt
1515
try:
@@ -507,7 +507,7 @@ def gitCheckForUpdates(fetch=True,g2repo=None):
507507
g2repo.remote().fetch()
508508
fetched = True
509509
except git.GitCommandError as msg:
510-
print(f'Failed to get updates from {g2repo.remote().url}')
510+
print(f'Failed to get updates from {g2repo.remote().url}\nerror: {msg}')
511511
try:
512512
head = g2repo.head.ref
513513
tracking = head.tracking_branch()
@@ -798,7 +798,8 @@ def InstallGitBinary(tarURL, instDir, nameByVersion=False, verbose=True):
798798
tar.close()
799799
if verbose: print(f'Downloading {tarURL}')
800800
r = requests.get(tarURL, allow_redirects=True)
801-
open(tar.name, 'wb').write(r.content)
801+
with open(tar.name, 'wb') as fp:
802+
fp.write(r.content)
802803
# open in tar
803804
tarobj = tarfile.open(name=tar.name)
804805
if nameByVersion:
@@ -928,7 +929,8 @@ def downloadDirContents(dirlist,targetDir,orgName=gitTutorialOwn, repoName=gitTu
928929
r = requests.get(URL, allow_redirects=True)
929930
outfil = os.path.join(targetDir,fil)
930931
if r.status_code == 200:
931-
open(outfil, 'wb').write(r.content)
932+
with open(outfil, 'wb') as fp:
933+
fp.write(r.content)
932934
print(f'wrote {outfil}')
933935
elif r.status_code == 404:
934936
print(f'Warning: {fil} is likely a subdirectory of directory {"/".join(dirlist)!r}')
@@ -1030,7 +1032,8 @@ def exceptHook(*args):
10301032
This routine is only used when debug=True is set in the configuration settings
10311033
'''
10321034
try:
1033-
from IPython.core import ultratb
1035+
#from IPython.core import ultratb
1036+
import IPython.core.ultratb
10341037
except:
10351038
pass
10361039

@@ -1082,6 +1085,7 @@ def InvokeDebugOpts():
10821085
global pdbBreak
10831086
pdbBreak = pdb.set_trace
10841087
import IPython
1088+
IPython
10851089
global IPyBreak
10861090
IPyBreak = IPyBreak_base
10871091
sys.excepthook = exceptHook
@@ -1093,11 +1097,23 @@ def InvokeDebugOpts():
10931097
os.environ['PYTHONBREAKPOINT'] = '0'
10941098

10951099
def TestSPG(fpth):
1100+
'''Test if pyspg.[so,.pyd] can be run from a location in the path
1101+
Do not modify the path if not.
1102+
'''
10961103
try:
10971104
from . import pyspg
1105+
pyspg
10981106
return True
10991107
except ImportError:
1100-
return _old_TestSPG(fpth)
1108+
return False
1109+
try:
1110+
pyspg.sgforpy('P -1')
1111+
except Exception as err:
1112+
print(70*'=')
1113+
print(f'Module pyspg in {fpth!r} could not be run\nerror msg: {err}')
1114+
print(70*'=')
1115+
return False
1116+
return True
11011117

11021118
def _old_TestSPG(fpth):
11031119
'''Test if pyspg.[so,.pyd] can be run from a location in the path
@@ -1158,11 +1174,12 @@ def SetBinaryPath(showConfigMsg=False):
11581174
global BinaryPathLoaded,binaryPath,BinaryPathFailed
11591175
if BinaryPathLoaded or BinaryPathFailed: return
11601176
try:
1161-
inpver = intver(np.__version__)
1177+
intver(np.__version__)
11621178
except (AttributeError,TypeError): # happens on building docs
11631179
return
11641180
try:
11651181
from GSASII import pypowder
1182+
pypowder
11661183
binaryPath = None # special value to indicate that binaries have been installed into package
11671184
if showConfigMsg:
11681185
print(f'GSAS-II binaries co-located with GSAS-II: {os.path.dirname(__file__)}')
@@ -1358,6 +1375,7 @@ def condaTest(requireAPI=False):
13581375
# is the conda package available?
13591376
try:
13601377
import conda.cli.python_api
1378+
conda.cli.python_api
13611379
except:
13621380
print('You do not have the conda package installed in this environment',
13631381
'\nConsider using the "conda install conda" command')
@@ -1567,12 +1585,12 @@ def addCondaPkg():
15671585
script += 'conda install conda -n '+currenv+' -y'
15681586
p = subprocess.Popen(script,shell=True,env={},
15691587
#stdout=subprocess.PIPE,
1570-
stderr=subprocess.PIPE)
1571-
out,err = MakeByte2str(p.communicate())
1572-
#print('Output from adding conda:\n',out)
1573-
if err:
1574-
print('Note error/warning:')
1575-
print(err)
1588+
stderr=subprocess.PIPE,
1589+
encoding='UTF-8')
1590+
out,err = p.communicate()
1591+
if out is not None and GetConfigValue('debug'): print('Output from adding conda:\n',out)
1592+
if err and err is not None:
1593+
print('Note error/warning from running conda:\n',err)
15761594
if currenv == "base":
15771595
print('\nUnexpected action: adding conda to base environment???')
15781596
#==============================================================================

GSASII/GSASIIphsGUI.py

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3043,7 +3043,8 @@ def _showWebPage(event):
30433043
txt = event.GetEventObject().page
30443044
tmp = tempfile.NamedTemporaryFile(suffix='.html',
30453045
delete=False)
3046-
open(tmp.name,'w').write(txt.replace(
3046+
with open(tmp.name,'w') as fp:
3047+
fp.write(txt.replace(
30473048
'<HEAD>',
30483049
'<head><base href="https://stokes.byu.edu/iso/">',
30493050
))
@@ -3100,7 +3101,8 @@ def _showWebPage(event):
31003101
flags=re.IGNORECASE)[0]
31013102
except IndexError:
31023103
tmp1 = tempfile.NamedTemporaryFile(suffix='.html')
3103-
open(tmp1.name,'w').write(r1.text.replace(
3104+
with open(tmp1.name,'w') as fp:
3105+
fp.write(r1.text.replace(
31043106
'<HEAD>',
31053107
'<head><base href="https://stokes.byu.edu/iso/">',
31063108
))
@@ -3273,7 +3275,8 @@ def _showWebPage(event):
32733275
num = event.GetEventObject().IndexNum
32743276
tmp = tempfile.NamedTemporaryFile(suffix='.html',
32753277
delete=False)
3276-
open(tmp.name,'w').write(pagelist[num].replace(
3278+
with open(tmp.name,'w') as fp:
3279+
fp.write(pagelist[num].replace(
32773280
'<head>',
32783281
'<head><base href="https://www.cryst.ehu.es/">',
32793282
))
@@ -3454,13 +3457,13 @@ def showSuperResults(G2frame,msgs,pagelist,fileList,ReSearch,parentpage,msg=None
34543457
'''Show a summary with info from a search of supergroups in
34553458
:func:`OnSuperSearch` (in :func:`UpdatePhaseData`)
34563459
'''
3457-
import SUBGROUPS
34583460
def _showWebPage(event):
34593461
import tempfile
34603462
f = event.GetEventObject().webFile
34613463
tmp = tempfile.NamedTemporaryFile(suffix='.html',
34623464
delete=False)
3463-
open(tmp.name,'w').write(f.replace(
3465+
with open(tmp.name,'w') as fp:
3466+
fp.write(f.replace(
34643467
'<head>',
34653468
'<head><base href="https://www.cryst.ehu.es/">',
34663469
))
@@ -7952,7 +7955,7 @@ def Runfullrmc(event):
79527955
shutil.rmtree(rmcname)
79537956
else:
79547957
return
7955-
G2G.G2MessageBox(G2frame,f'For use of fullrmc, please cite:\n\n'+
7958+
G2G.G2MessageBox(G2frame,'For use of fullrmc, please cite:\n\n'+
79567959
G2G.GetCite('fullrmc')+
79577960
'\n\nNote: A more advanced version of fullrmc can be found at www.fullrmc.com',
79587961
'Please cite fullrmc')
@@ -8014,7 +8017,7 @@ def RunRMCProfile(event):
80148017
rmcexe = os.path.split(rmcfile)[0]
80158018
#print(rmcexe)
80168019
wx.MessageBox(
8017-
f' For use of RMCProfile, please cite:\n\n'+
8020+
' For use of RMCProfile, please cite:\n\n'+
80188021
G2G.GetCite("RMCProfile"),
80198022
caption='RMCProfile',style=wx.ICON_INFORMATION)
80208023
if os.path.isfile(pName+'.his6f'):
@@ -17004,6 +17007,7 @@ def checkPDFfit(G2frame):
1700417007
# see if diffpy has been installed directly
1700517008
try:
1700617009
from diffpy.pdffit2 import PdfFit
17010+
PdfFit
1700717011
return True
1700817012
except:
1700917013
pass
@@ -17012,6 +17016,7 @@ def checkPDFfit(G2frame):
1701217016
# Python in a separate environment
1701317017
try: # have conda. Can we access it programmatically?
1701417018
import conda.cli.python_api
17019+
conda.cli.python_api
1701517020
except:
1701617021
G2G.G2MessageBox(G2frame,'You are running a directly installed Python. You will need to install PDFfit2 directly as well, preferably in a separate virtual environment.')
1701717022
return

GSASII/GSASIIpwd.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3457,7 +3457,8 @@ def fullrmcDownload():
34573457
'https://github.com/bachiraoun/fullrmc/tree/master/standalones',
34583458
'\nCreating '+fil,
34593459
'\nThis may take a while...')
3460-
open(fil, "wb").write(requests.get(URL).content)
3460+
with open(fil, "wb") as fp:
3461+
fp.write(requests.get(URL).content)
34613462
print('...Download completed')
34623463
if setXbit:
34633464
import stat
@@ -3474,6 +3475,8 @@ def findPDFfit():
34743475
try:
34753476
from diffpy.pdffit2 import PdfFit
34763477
import diffpy
3478+
PdfFit
3479+
diffpy
34773480
return sys.executable
34783481
except Exception as msg:
34793482
print('Error importing PDFfit2:\n',msg)

GSASII/GSASIIpwdGUI.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5153,15 +5153,15 @@ def _showWebPage(event):
51535153
import tempfile
51545154
txt = event.GetEventObject().page
51555155
tmp = tempfile.NamedTemporaryFile(suffix='.html',delete=False)
5156-
open(tmp.name,'w').write(txt.replace('<HEAD>',
5157-
'<head><base href="https://stokes.byu.edu/iso/">',))
5156+
with open(tmp.name,'w') as fp:
5157+
fp.write(txt.replace('<HEAD>','<head><base href="https://stokes.byu.edu/iso/">',))
51585158
fileList.append(tmp.name)
51595159
G2G.ShowWebPage('file://'+tmp.name,G2frame)
51605160
def showWebtext(txt):
51615161
import tempfile
51625162
tmp = tempfile.NamedTemporaryFile(suffix='.html',delete=False)
5163-
open(tmp.name,'w').write(txt.replace('<HEAD>',
5164-
'<head><base href="https://stokes.byu.edu/iso/">',))
5163+
with open(tmp.name,'w') as fp:
5164+
fp.write(txt.replace('<HEAD>','<head><base href="https://stokes.byu.edu/iso/">',))
51655165
fileList.append(tmp.name)
51665166
G2G.ShowWebPage('file://'+tmp.name,G2frame)
51675167

@@ -5273,7 +5273,7 @@ def _get_opt_val(opt_name, out):
52735273
data["origintype"] = "method2"
52745274
data["orderparam"] = radio_val + '" CHECKED'
52755275
data["isofilename"] = ""
5276-
out5 = requests.post(isoformsite, data=data).text
5276+
requests.post(isoformsite, data=data).text
52775277

52785278
continue
52795279

GSASII/ISODISTORT.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,8 @@
1515
isoformsite = 'https://iso.byu.edu/iso/isodistortform.php'
1616

1717
def HandleError(out):
18-
open('out.html','wb').write(out.encode("utf-8"))
18+
with open('out.html','wb') as fp:
19+
fp.write(out.encode("utf-8"))
1920
url = os.path.realpath('out.html')
2021
try:
2122
os.startfile(url)
@@ -263,7 +264,8 @@ def GetISODISTORTcif(Phase):
263264
# print(item,data2[item])
264265
out4 = requests.post(isoformsite,data=data2).text
265266
#print(out4)
266-
#open('pyout4.html','wb').write(out4.encode("utf-8"))
267+
#with open('pyout4.html','wb') as fp:
268+
#fp.write(out4.encode("utf-8"))
267269

268270
#retrieve data needed for next(last) step
269271

GSASII/SUBGROUPS.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -378,8 +378,10 @@ def GetSupergroup(SGnum,dlg=None):
378378
out1 = GSASIIpath.postURL(Site,{'gnum':SGnum,'show':'show','click':click}
379379
,timeout=timeout)
380380
if not out1: return None
381-
#open(f'/tmp/{click}.html','w').write(out1)
382-
#open(f'/tmp/last.html','w').write(out1)
381+
#with open(f'/tmp/{click}.html','w') as fp:
382+
# fp.write(out1)
383+
#with open(f'/tmp/last.html','w') as fp:
384+
# fp.write(out1)
383385
if dlg: dlg.Update(2+i,newmsg=f'processing {line[1]}, #{i+1} of {len(xforms)}')
384386
mvlist = []
385387
for s in [i.split('</pre>')[0] for i in out1.split('<pre>')[1::2]]:
@@ -556,7 +558,8 @@ def BilbaoSymSearch1(sgnum, phase, maxdelta=2, angtol=None,
556558
return scanBilbaoSymSearch1(page0,postdict)+[savedcookies]
557559

558560
def scanBilbaoSymSearch1(page0,postdict):
559-
#open(f'/tmp/pseudosym0.html','w').write(page0)
561+
#open(f'/tmp/pseudosym0.html','w') as fp:
562+
# fp.write(page0)
560563
valsdict = {} # base for all supergroups
561564
csdict = {} # supergroups w/default selection value
562565
rowdict = {} # information in table row for each supergroup

GSASII/install/makeLinux.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
The path to Python is determined from the version of Python used to
2525
run this script.
2626
'''
27-
import sys, os, os.path, stat, shutil, subprocess, plistlib
27+
import sys, os, os.path, stat, shutil
2828
import datetime
2929
desktop_template = """
3030
[Desktop Entry]
@@ -104,7 +104,6 @@ def Usage():
104104
stat.S_IXUSR | stat.S_IRUSR | stat.S_IRGRP | stat.S_IXGRP | stat.S_IXOTH)
105105

106106
script = ''
107-
import shutil
108107
for term in ("lxterminal", "gnome-terminal", 'konsole', "xterm",
109108
"terminator", "terminology", "tilix"):
110109
try:
@@ -151,9 +150,8 @@ def Usage():
151150
for f,t in zip((dfile,mfile),('Desktop','Menu')):
152151
if f is None: continue
153152
try:
154-
open(f,'w').write(desktop_template.format(
155-
terminal,
156-
G2start+add2script,G2icon))
153+
with open(f,'w') as fp:
154+
fp.write(desktop_template.format(terminal,G2start+add2script,G2icon))
157155
os.chmod(
158156
dfile,
159157
stat.S_IWUSR | stat.S_IXUSR | stat.S_IRUSR | stat.S_IRGRP | stat.S_IXGRP | stat.S_IXOTH)

GSASII/install/makeMacApp.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -76,8 +76,7 @@
7676
'''
7777

7878
from __future__ import division, print_function
79-
import sys, os, os.path, stat, shutil, subprocess, plistlib
80-
import platform
79+
import sys, os, os.path, subprocess
8180
def Usage():
8281
print(f"\nUsage:\n\tpython {os.path.abspath(sys.argv[0])} [install_path] [<GSAS-II_script>] [Python_loc]\n")
8382
sys.exit()
@@ -147,7 +146,8 @@ def Usage():
147146
print(f"\nRemoving {g2Name!r}")
148147
os.remove(g2Name)
149148
#os.symlink(G2script,g2Name)
150-
open(g2Name,'w').write('''# this script starts GSAS-II when not installed into Python
149+
with open(g2Name,'w') as fp:
150+
fp.write('''# this script starts GSAS-II when not installed into Python
151151
# it will be called from the GSAS-II.app AppleScript
152152
# it should be not be renamed or moved
153153
import sys,os

0 commit comments

Comments
 (0)