Skip to content
Advertisement

merge python script and data (command) file into single .py file

Below scrip reads lines of commands to execute from a cmdAll.txt. Is there a way that I merge the command file into the script file itself. I remember I have seen such data blocks using <<EOF somewhere but I am not sure how to do it.

myScript.py file:

#!/usr/bin/python
i=1
import enms
s = enms.open()
with open('cmdAll.txt') as f:
    for cmd in f:
        r = s.terminal().execute(cmd)
        filename = "output_%d.txt" % i
        fp = open(filename, 'w')
        for line in r.get_output():
            print line
            fp.write(line + "n")
        fp.close()
        i+=1
f.close()
enms.close(s)

cmdAll.txt file:

cmget get * en.(enbid) -t
cmget get * gn.(gnbid) -t
cmget get * gnssinfo.(latitude,longitude) --table
cmget get * GpsSyncRef.(latitude,longitude) --table

Advertisement

Answer

I think the <<EOF bit you saw somewhere had to do with running Python in a shell script in a shell script, but you’re asking for the inverse. You want your shell commands to live in your python script.

If you’re not going to read the commands from a .txt file, and you would rather they live in the script, you might as well just make it clean and make a list out of them.

import enms

cmds = [
    "cmget get * en.(enbid) -t",
    "cmget get * gn.(gnbid) -t",
    "cmget get * gnssinfo.(latitude,longitude) --table",
    "cmget get * GpsSyncRef.(latitude,longitude) --table"
]

s = enms.open()
for cmd in cmds:
    r = s.terminal().execute(cmd)

If you prefer the commands exist as a single string, you could do something like this, where you are splitting on newlines. Just as Eric Jin suggested

import enms

comds = '''cmget get * en.(enbid) -t
cmget get * gn.(gnbid) -t
cmget get * gnssinfo.(latitude,longitude) --table
cmget get * GpsSyncRef.(latitude,longitude) --table'''

s = enms.open()
for cmd in cmds.split("n"):
    r = s.terminal().execute(cmd)

Advertisement