Skip to content

Remove labscript_suite from default config file #45

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion labscript_profile/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ def add_userlib_and_pythonlib():
time the interpreter starts up"""
labconfig = default_labconfig_path()
if labconfig is not None and labconfig.exists():
config = ConfigParser()
config = ConfigParser(defaults={'labscript_suite': LABSCRIPT_SUITE_PROFILE})
config.read(labconfig)
for option in ['userlib', 'pythonlib']:
try:
Expand Down
3 changes: 1 addition & 2 deletions labscript_profile/create.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,8 @@ def make_labconfig_file():
outfile.write(data)

# Now change some things about it:
config = configparser.ConfigParser()
config = configparser.ConfigParser(interpolation=None)
config.read(target_path)
config.set('DEFAULT', 'labscript_suite', str(LABSCRIPT_SUITE_PROFILE))
if sys.platform in ['linux', 'linux2']:
config.set('programs', 'text_editor', 'gedit')
elif sys.platform == 'darwin':
Expand Down
1 change: 0 additions & 1 deletion labscript_profile/default_profile/labconfig/example.ini
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
experiment_name = default_experiment
shared_drive = C:
experiment_shot_storage = %(shared_drive)s\Experiments\%(experiment_name)s
labscript_suite = C:\labscript_suite
userlib=%(labscript_suite)s\userlib
pythonlib = %(userlib)s\pythonlib
labscriptlib = %(userlib)s\labscriptlib\%(experiment_name)s
Expand Down
114 changes: 27 additions & 87 deletions labscript_utils/labconfig.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,48 +12,13 @@
#####################################################################
import sys
import os
import socket
import subprocess
import errno
import configparser

from labscript_profile import LABSCRIPT_SUITE_PROFILE
# Look for a 'labconfig' folder in the labscript install directory:
if LABSCRIPT_SUITE_PROFILE is not None:
config_prefix = os.path.join(LABSCRIPT_SUITE_PROFILE, 'labconfig')
else:
# No labscript install directory found? Revert to system defaults
if os.name == 'nt':
config_prefix = os.path.abspath(r'C:\labconfig')
else:
config_prefix = os.path.join(os.getenv('HOME'),'labconfig')
if not os.path.exists(config_prefix):
config_prefix='/etc/labconfig/'
from labscript_utils import dedent
from labscript_profile import default_labconfig_path, LABSCRIPT_SUITE_PROFILE

if not os.path.exists(config_prefix):
message = (r"Couldn't find labconfig folder. Please ensure it exists. " +
r"If the labscript suite is installed, labconfig must be <labscript_suite_profile>/labconfig/. " +
r"If the labscript suite is not installed, then C:\labconfig\ is checked on Windows, " +
r" and $HOME/labconfig/ then /etc/labconfig/ checked on unix.")
raise IOError(message)
default_config_path = default_labconfig_path()

config_prefix = os.path.abspath(config_prefix)

if sys.platform == 'darwin':
hostname = subprocess.check_output(['scutil', '--get', 'LocalHostName']).decode('utf8').strip()
else:
hostname = socket.gethostname()
default_config_path = os.path.join(config_prefix,'%s.ini'%hostname)


def mkdir_p(path):
try:
os.makedirs(path)
except OSError as exc:
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise

class EnvInterpolation(configparser.BasicInterpolation):
"""Interpolation which expands environment variables in values,
Expand All @@ -63,69 +28,44 @@ def before_get(self, *args):
value = super(EnvInterpolation, self).before_get(*args)
return os.path.expandvars(value)


class LabConfig(configparser.ConfigParser):
NoOptionError = configparser.NoOptionError
NoSectionError = configparser.NoSectionError

def __init__(self,config_path=default_config_path,required_params={},defaults={}):
if isinstance(config_path,list):
def __init__(
self, config_path=default_config_path, required_params=None, defaults=None,
):
if required_params is None:
required_params = {}
if defaults is None:
defaults = {}
defaults['labscript_suite'] = LABSCRIPT_SUITE_PROFILE
if isinstance(config_path, list):
self.config_path = config_path[0]
else:
self.config_path = config_path

self.file_format = ""
for section, options in required_params.items():
self.file_format += "[%s]\n"%section
self.file_format += "[%s]\n" % section
for option in options:
self.file_format += "%s = <value>\n"%option

# Ensure the folder exists:
mkdir_p(os.path.dirname(self.config_path))

# If the file doesn't exist, create it
if not os.path.exists(self.config_path):
with open(self.config_path,'a+') as f:
f.write(self.file_format)
self.file_format += "%s = <value>\n" % option

# Load the config file
configparser.ConfigParser.__init__(self, defaults=defaults, interpolation=EnvInterpolation())
self.read(config_path) #read all files in the config path if it is a list (self.config_path only contains one string)
configparser.ConfigParser.__init__(
self, defaults=defaults, interpolation=EnvInterpolation()
)
# read all files in the config path if it is a list (self.config_path only
# contains one string):
self.read(config_path)

try:
for section, options in required_params.items():
for option in options:
self.get(section,option)

except configparser.NoOptionError as e:
raise Exception('The experiment configuration file located at %s does not have the required keys. Make sure the config file containes the following structure:\n%s'%(config_path, self.file_format))


# Overwrite the add_section method to only attempt to add a section if it doesn't
# exist. We don't ever care whether a section exists or not, only that it does exist
# when we try and save an attribute into it.
def add_section(self,section):
# Create the group if it doesn't exist
if not section.lower() == 'default' and not self.has_section(section):
configparser.ConfigParser.add_section(self, section)

# Overwrite the set method so that it adds the section if it doesn't exist,
# and immediately saves the data to the file (to avoid data loss on program crash)
def set(self, section, option, value):
self.add_section(section)
configparser.ConfigParser.set(self,section,option,value)
self.save()

# Overwrite the remove section function so that it immediately saves the change to disk
def remove_section(self,section):
configparser.ConfigParser.remove_section(self,section)
self.save()

# Overwrite the remove option function so that it immediately saves the change to disk
def remove_option(self,section,option):
configparser.ConfigParser.remove_option(self,section,option)
self.save()

# Provide a convenience method to save the contents of the ConfigParser to disk
def save(self):
with open(self.config_path, 'w+') as f:
self.write(f)
self.get(section, option)
except configparser.NoOptionError:
msg = f"""The experiment configuration file located at {config_path} does
not have the required keys. Make sure the config file containes the
following structure:\n{self.file_format}"""
raise Exception(dedent(msg))