Skip to content

Commit a332a96

Browse files
committed
address some windows issues: rename GSASII.py to G2.py to avoid import issues; fix import of importlib.util; xfer config.py to config.ini automatically
1 parent 7b65f99 commit a332a96

File tree

12 files changed

+184
-292
lines changed

12 files changed

+184
-292
lines changed

.gitignore

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
# obsolete GSAS-II settings file
2+
config.py
3+
14
# local code for debugging
25
debug_setup.py.example
36
debug_setup.py

GSASII/GSASII.py renamed to GSASII/G2.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99

1010
import os
1111
import sys
12-
import importlib
12+
import importlib.util
1313
try:
1414
pkginfo = importlib.util.find_spec('GSASII.GSASIIGUI')
1515
except ModuleNotFoundError:

GSASII/GSASIIctrlGUI.py

Lines changed: 2 additions & 116 deletions
Original file line numberDiff line numberDiff line change
@@ -6434,8 +6434,8 @@ def SaveConfigVars(vars,parent=None):
64346434
'''Write the current config variable values to ~/.GSASII/config.ini
64356435
64366436
:params dict vars: a dictionary of variable settings and meanings as
6437-
created in :func:`GetConfigValsDocs`. Most of the information gathered
6438-
in GetConfigValsDocs is no longer used here.
6437+
created in :func:`GetConfigValsDocs`. Most of the information gathered
6438+
in GetConfigValsDocs is no longer used here.
64396439
:param parent: wx.Frame object or None. No longer used.
64406440
:returns: True if unable to write the file, None otherwise
64416441
'''
@@ -9032,120 +9032,6 @@ def onTimer(self,event):
90329032
self.msgpos += 1
90339033
if self.msgpos >= len(self.fullmsg): self.msgpos = 0
90349034

9035-
#===========================================================================
9036-
# this has been moved to GSASIIfiles, since it does not need wx
9037-
# def openInNewTerm(project=None,g2script=None,pythonapp=sys.executable):
9038-
# '''Open a new and independent GSAS-II session in separate terminal
9039-
# or console window and as a separate process that will continue
9040-
# even if the calling process exits.
9041-
# Intended to work on all platforms.
9042-
9043-
# This could be used to run other scripts inside python other than GSAS-II
9044-
9045-
# :param str project: the name of an optional parameter to be
9046-
# passed to the script (usually a .gpx file to be opened in
9047-
# a new GSAS-II session)
9048-
# :param str g2script: the script to be run. If None (default)
9049-
# the GSASII.py file in the same directory as this file will
9050-
# be used.
9051-
# :param str pythonapp: the Python interpreter to be used.
9052-
# Defaults to sys.executable which is usually what is wanted.
9053-
# :param str terminal: a name for a preferred terminal emulator
9054-
# '''
9055-
# import subprocess
9056-
# if g2script is None:
9057-
# g2script = os.path.join(os.path.dirname(__file__),'GSASII.py')
9058-
9059-
# if sys.platform == "darwin":
9060-
# if project:
9061-
# script = f'''
9062-
# set python to "{pythonapp}"
9063-
# set appwithpath to "{g2script}"
9064-
# set filename to "{project}"
9065-
# set filename to the quoted form of the POSIX path of filename
9066-
9067-
# tell application "Terminal"
9068-
# activate
9069-
# do script python & " " & appwithpath & " " & filename & "; exit"
9070-
# end tell
9071-
# '''
9072-
# else:
9073-
# script = f'''
9074-
# set python to "{pythonapp}"
9075-
# set appwithpath to "{g2script}"
9076-
9077-
# tell application "Terminal"
9078-
# activate
9079-
# do script python & " " & appwithpath & " " & "; exit"
9080-
# end tell
9081-
# '''
9082-
# subprocess.Popen(["osascript","-e",script])
9083-
# elif sys.platform.startswith("win"):
9084-
# cmds = [pythonapp, g2script]
9085-
# if project: cmds += [project]
9086-
# subprocess.Popen(cmds,creationflags=subprocess.CREATE_NEW_CONSOLE)
9087-
# else:
9088-
# import shutil
9089-
# script = ''
9090-
# # try a bunch of common terminal emulators in Linux
9091-
# # there does not appear to be a good way to way to specify this
9092-
# # perhaps this should be a GSAS-II config option
9093-
# for term in ("lxterminal", "gnome-terminal", 'konsole', "xterm",
9094-
# "terminator", "terminology", "tilix"):
9095-
# try:
9096-
# found = shutil.which(term)
9097-
# if not found: continue
9098-
# except AttributeError:
9099-
# print(f'shutil.which() failed (why?); assuming {term} present')
9100-
# found = True
9101-
# if term == "gnome-terminal":
9102-
# #terminal = 'gnome-terminal -t "GSAS-II console" --'
9103-
# cmds = [term,'--title','"GSAS-II console"','--']
9104-
# script = "echo; echo Press Enter to close window; read line"
9105-
# break
9106-
# elif term == "lxterminal":
9107-
# #terminal = 'lxterminal -t "GSAS-II console" -e'
9108-
# cmds = [term,'-t','"GSAS-II console"','-e']
9109-
# script = "echo;echo Press Enter to close window; read line"
9110-
# break
9111-
# elif term == "xterm":
9112-
# #terminal = 'xterm -title "GSAS-II console" -hold -e'
9113-
# cmds = [term,'-title','"GSAS-II console"','-hold','-e']
9114-
# script = "echo; echo This window can now be closed"
9115-
# break
9116-
# elif term == "terminator":
9117-
# cmds = [term,'-T','"GSAS-II console"','-x']
9118-
# script = "echo;echo Press Enter to close window; read line"
9119-
# break
9120-
# elif term == "konsole":
9121-
# cmds = [term,'-p','tabtitle="GSAS-II console"','--hold','-e']
9122-
# script = "echo; echo This window can now be closed"
9123-
# break
9124-
# elif term == "tilix":
9125-
# cmds = [term,'-t','"GSAS-II console"','-e']
9126-
# script = "echo;echo Press Enter to close window; read line"
9127-
# break
9128-
# elif term == "terminology":
9129-
# cmds = [term,'-T="GSAS-II console"','--hold','-e']
9130-
# script = "echo; echo This window can now be closed"
9131-
# break
9132-
# else:
9133-
# print("No known terminal was found to use, Can't start {}")
9134-
# return
9135-
9136-
# fil = '/tmp/GSAS2-launch.sh'
9137-
# cmds += ['/bin/sh',fil]
9138-
# fp = open(fil,'w')
9139-
# if project:
9140-
# fp.write(f"{pythonapp} {g2script} {project}\n")
9141-
# else:
9142-
# fp.write(f"{pythonapp} {g2script}\n")
9143-
# fp.write(f"rm {fil}\n")
9144-
# if script:
9145-
# fp.write(f"{script}\n")
9146-
# fp.close()
9147-
# subprocess.Popen(cmds,start_new_session=True)
9148-
91499035
#===========================================================================
91509036
def ExtractFileFromZip(filename, selection=None, confirmread=True,
91519037
confirmoverwrite=True, parent=None,

GSASII/GSASIIdataGUI.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4367,7 +4367,6 @@ def OnNewGSASII(self, event):
43674367
self.LastGPXdir = dlg.GetDirectory()
43684368
finally:
43694369
dlg.Destroy()
4370-
#G2script = os.path.join(os.path.split(__file__)[0],'GSASII.py')
43714370
G2fil.openInNewTerm(GSASprojectfile)
43724371

43734372
def SetTitleByGPX(self):
@@ -8607,7 +8606,7 @@ def OnShowShift(event):
86078606
G2frame.PatternId = item
86088607
data = G2frame.GPXtree.GetItemPyData(GetGPXtreeItemId(G2frame,item,'PDF Controls'))
86098608
G2pdG.UpdatePDFGrid(G2frame,data)
8610-
for i in G2frame.ExportPDF: i.Enable(True) # this should be done on .gpx load; is done on OnMakePDFs (GSASII.py)
8609+
for i in G2frame.ExportPDF: i.Enable(True) # this should be done on .gpx load; is done on OnMakePDFs
86118610
if len(data['G(R)']):
86128611
G2plt.PlotISFG(G2frame,data,plotType='G(R)')
86138612
elif G2frame.GPXtree.GetItemText(item) == 'Phases':
@@ -8677,7 +8676,7 @@ def OnShowShift(event):
86778676
G2frame.PatternId = G2frame.GPXtree.GetItemParent(item)
86788677
data = G2frame.GPXtree.GetItemPyData(item)
86798678
G2pdG.UpdatePDFGrid(G2frame,data)
8680-
for i in G2frame.ExportPDF: i.Enable(True) # this should be done on .gpx load; is done on OnMakePDFs (GSASII.py)
8679+
for i in G2frame.ExportPDF: i.Enable(True) # this should be done on .gpx load; is done on OnMakePDFs
86818680
if len(data['G(R)']):
86828681
if 'I(Q)' in data: G2plt.PlotISFG(G2frame,data,plotType='I(Q)')
86838682
if 'S(Q)' in data: G2plt.PlotISFG(G2frame,data,plotType='S(Q)')

GSASII/GSASIIfiles.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1473,15 +1473,15 @@ def openInNewTerm(project=None,g2script=None,pythonapp=sys.executable):
14731473
passed to the script (usually a .gpx file to be opened in
14741474
a new GSAS-II session)
14751475
:param str g2script: the script to be run. If None (default)
1476-
the GSASII.py file in the same directory as this file will
1476+
the G2.py file in the same directory as this file will
14771477
be used.
14781478
:param str pythonapp: the Python interpreter to be used.
14791479
Defaults to sys.executable which is usually what is wanted.
14801480
:param str terminal: a name for a preferred terminal emulator
14811481
'''
14821482
import subprocess
14831483
if g2script is None:
1484-
g2script = os.path.join(os.path.dirname(__file__),'GSASII.py')
1484+
g2script = os.path.join(os.path.dirname(__file__),'G2.py')
14851485

14861486
if sys.platform == "darwin":
14871487
if project:

GSASII/GSASIIpath.py

Lines changed: 49 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -36,16 +36,16 @@
3636
intver = lambda vs: sum([int(i) for i in vs.split('.')[0:2]]*np.array((1000,1)))
3737

3838
def GetConfigValue(key,default=None,getDefault=False):
39-
'''Return the configuration file value for key or a default value
39+
'''Return the configuration file value for key or a default value
4040
if not specified.
41-
41+
4242
:param str key: a value to be found in the configuration settings
43-
:param any default: a value to be supplied if a value for key is
44-
not specified in the config file or the config file is not found.
43+
:param any default: a value to be supplied if a value for key is
44+
not specified in the config file or the config file is not found.
4545
Defaults to None.
46-
:param bool getDefault: If True looks up the default value from the
47-
config_example.py file (default value is False). Do not specify a
48-
getDefault=True if a value is provided for default.
46+
:param bool getDefault: If True looks up the default value from the
47+
config_example.py file (default value is False). Do not specify a
48+
getDefault=True if a value is provided for default.
4949
:returns: the value found or the default.
5050
'''
5151
if getDefault:
@@ -58,11 +58,11 @@ def GetConfigValue(key,default=None,getDefault=False):
5858
return None
5959

6060
def SetConfigValue(parmdict):
61-
'''Set configuration variables. Note that parmdict is a dictionary
62-
from :func:`GSASIIctrlGUI.GetConfigValsDocs` where each element is a
63-
lists. The first item in list is the default value, the second is
64-
the value to use for that configuration variable. Most of the
65-
information gathered in GetConfigValsDocs is no longer used.
61+
'''Set configuration variables. Note that parmdict is a dictionary
62+
from :func:`GSASIIctrlGUI.GetConfigValsDocs` where each element is a
63+
lists. The first item in list is the default value, the second is
64+
the value to use for that configuration variable. Most of the
65+
information gathered in GetConfigValsDocs is no longer used.
6666
'''
6767
global configDict
6868
for var in parmdict:
@@ -924,7 +924,7 @@ def runScript(cmds=[], wait=False, G2frame=None):
924924
projectfile = ''
925925
if G2frame.GSASprojectfile:
926926
projectfile = os.path.realpath(G2frame.GSASprojectfile)
927-
main = os.path.join(path2GSAS2,'GSASII.py')
927+
main = os.path.join(path2GSAS2,'G2.py')
928928
ex = sys.executable
929929
if sys.platform == "darwin": # mac requires pythonw which is not always reported as sys.executable
930930
if os.path.exists(ex+'w'): ex += 'w'
@@ -946,7 +946,7 @@ def runScript(cmds=[], wait=False, G2frame=None):
946946

947947
def IPyBreak_base(userMsg=None):
948948
'''A routine that invokes an IPython session at the calling location
949-
This routine is only used when debug=True is set in the configuration
949+
This routine is only used when debug=True is set in the configuration
950950
settings
951951
'''
952952
savehook = sys.excepthook # save the exception hook
@@ -979,7 +979,7 @@ def exceptHook(*args):
979979
'''A routine to be called when an exception occurs. It prints the traceback
980980
with fancy formatting and then calls an IPython shell with the environment
981981
of the exception location.
982-
982+
983983
This routine is only used when debug=True is set in the configuration settings
984984
'''
985985
try:
@@ -1026,7 +1026,7 @@ def DoNothing():
10261026
pass
10271027

10281028
def InvokeDebugOpts():
1029-
'Called in GSASII.py to set up debug options'
1029+
'Called to set up debug options'
10301030
if any('SPYDER' in name for name in os.environ):
10311031
print('Running from Spyder, keeping breakpoint() active & skipping exception trapping')
10321032
elif GetConfigValue('debug'):
@@ -1136,13 +1136,13 @@ def SetBinaryPath(showConfigMsg=False):
11361136
BinaryPathFailed = pathHacking._path_discovery(showConfigMsg)
11371137

11381138
def WriteConfig(configDict):
1139-
'''Write the configDict information to the GSAS-II ini settings
1140-
into file ~/.GSASII/config.ini. Called from
1139+
'''Write the configDict information to the GSAS-II ini settings
1140+
into file ~/.GSASII/config.ini. Called from
11411141
:func:`GSASIIctrlGUI.SaveConfigVars`.
11421142
'''
11431143
import configparser
1144-
1145-
localdir = os.path.expanduser('~/.GSASII')
1144+
1145+
localdir = os.path.expanduser(os.path.normpath('~/.GSASII'))
11461146
if not os.path.exists(localdir):
11471147
try:
11481148
os.mkdir(g2local)
@@ -1166,13 +1166,37 @@ def LoadConfig(printInfo=True):
11661166
:param bool printInfo: if printInfo is True (default) then a message
11671167
is shown with the number of settings read (upon startup).
11681168
'''
1169+
def XferConfigIni():
1170+
'''copy the contents of the config.py file to file ~/.GSASII/config.ini.
1171+
This "patch code" used for master->develop transition and can eventually
1172+
be removed.
1173+
'''
1174+
import types
1175+
configDict = {}
1176+
try:
1177+
import config
1178+
#import config_example as config
1179+
for i in config.__dict__:
1180+
if i.startswith('__') and i.endswith('__'): continue
1181+
if isinstance(config.__dict__[i],types.ModuleType): continue
1182+
configDict.update({i:str(config.__dict__[i])})
1183+
except ImportError as err:
1184+
print("Error importing config.py file\n",err)
1185+
return
1186+
except Exception as err:
1187+
print("Error reading config.py file\n",err)
1188+
return
1189+
print(f"Contents of {config.__file__} to be written...")
1190+
WriteIniConfi(configDict)
1191+
11691192
import configparser
11701193
global configDict
11711194
configDict = {}
1172-
cfgfile = os.path.expanduser('~/.GSASII/config.ini')
1195+
cfgfile = os.path.expanduser(os.path.normpath('~/.GSASII/config.ini'))
11731196
if not os.path.exists(cfgfile):
11741197
print(f'N.B. Configuration file {cfgfile} does not exist')
1175-
return
1198+
# patch 2/7/25: transform GSAS-II config.py contents to config.ini
1199+
XferConfigIni()
11761200
try:
11771201
from . import config_example
11781202
except ImportError as err:
@@ -1201,7 +1225,7 @@ def LoadConfig(printInfo=True):
12011225
try:
12021226
if cfgG[key] == 'None':
12031227
configDict[capKey] = None
1204-
elif key.endswith('_pos') or key.endswith('_size'): # list of integers
1228+
elif key.endswith('_pos') or key.endswith('_size'): # list of integers
12051229
configDict[capKey] = tuple([int(i) for i in
12061230
cfgG[key].strip('()').split(',')])
12071231
elif key.endswith('_location') or key.endswith('_directory') or key.endswith('_exec'): # None (above) or str
@@ -1212,7 +1236,7 @@ def LoadConfig(printInfo=True):
12121236
res = []
12131237
else:
12141238
res = [i.strip("'").replace(r'\\','\\') for i in s.split(', ')]
1215-
configDict[capKey] = res
1239+
configDict[capKey] = res
12161240
elif isinstance(config_example.__dict__[capKey],bool):
12171241
configDict[capKey] = cfgG.getboolean(key)
12181242
elif isinstance(config_example.__dict__[capKey],float):
@@ -1230,41 +1254,6 @@ def LoadConfig(printInfo=True):
12301254
print (f'{len(configDict)} values read from {cfgfile}')
12311255
# make sure this value is set
12321256
configDict['Clip_on'] = configDict.get('Clip_on',True)
1233-
1234-
# def MacStartGSASII(g2script,project=''):
1235-
# '''Start a new instance of GSAS-II by opening a new terminal window and starting
1236-
# a new GSAS-II process. Used on Mac OS X only.
1237-
1238-
# :param str g2script: file name for the GSASII.py script
1239-
# :param str project: GSAS-II project (.gpx) file to be opened, default is blank
1240-
# which opens a new project
1241-
# '''
1242-
# if project and os.path.splitext(project)[1] != '.gpx':
1243-
# print(f'file {project} cannot be used. Not GSAS-II project (.gpx) file')
1244-
# return
1245-
# if project and not os.path.exists(project):
1246-
# print(f'file {project} cannot be found.')
1247-
# return
1248-
# elif project:
1249-
# project = os.path.abspath(project)
1250-
# if not os.path.exists(project):
1251-
# print(f'lost project {project} with abspath')
1252-
# raise Exception(f'lost project {project} with abspath')
1253-
# g2script = os.path.abspath(g2script)
1254-
# pythonapp = sys.executable
1255-
# if os.path.exists(pythonapp+'w'): pythonapp += 'w'
1256-
# script = f'''
1257-
# set python to "{pythonapp}"
1258-
# set appwithpath to "{g2script}"
1259-
# set filename to "{project}"
1260-
# set filename to the quoted form of the POSIX path of filename
1261-
1262-
# tell application "Terminal"
1263-
# activate
1264-
# do script python & " " & appwithpath & " " & filename & "; exit"
1265-
# end tell
1266-
# '''
1267-
# subprocess.Popen(["osascript","-e",script])
12681257

12691258
def MacRunScript(script):
12701259
'''Start a bash script in a new terminal window.
@@ -1944,7 +1933,7 @@ def postURL(URL,postdict,getcookie=None,usecookie=None,
19441933

19451934
if gitUpdate:
19461935
# now restart GSAS-II with the new version
1947-
# G2scrpt = os.path.join(path2GSAS2,'GSASII.py')
1936+
# G2scrpt = os.path.join(path2GSAS2,'G2.py')
19481937
if project:
19491938
print(f"Restart GSAS-II with project file {project!r}")
19501939
# subprocess.Popen([sys.executable,G2scrpt,project])

0 commit comments

Comments
 (0)