I am trying to read variables from cshell file output by an application. The application assumes we are using cshell to read the variables. I am using Python.
The file contains two (T)csh wordlist shell variables lnPARAM and lnVAL;
set lnPARAM = ('path' 'job' 'delete_source' )
set lnVAL = ('/opt/genesis/fw/jobs/48039/input' '48039' 'no' )
I would like to create variables for path, job and delete_source set to strings '/opt/..', '48039' and 'no'.
I have split the lines to a list;
>>> line0 = "set lnPARAM = ('path' 'job' 'delete_source' )"
>>> line1 = "set lnVAL = ('/opt/genesis/fw/jobs/48039/input' '48039' 'no' )"
>>> ln_param = [value.strip("'") for value in line0.split(' = ')[1].lstrip('(').rstrip(')').split(' ') if value != '']
>>> ln_val = [value.strip("'") for value in line1.split(' = ')[1].lstrip('(').rstrip(')').split(' ') if value != '']
>>> r = dict(zip(ln_param, ln_val))
>>> r['path']
'/opt/genesis/fw/jobs/48039/input'
shlex does not seem to be the solution.
>>>import shlex
>>> shlex.split(line0)
['set', 'lnPARAM', '=', '(path', 'job', 'delete_source', ')']
I am hoping someone else has a more elegant solution than the one I assembled.
You can extract the string enclosed in parentheses before passing it to shlex.split
:
import re
shlex.split(re.findall(r'\((.*)\)', line0)[0])