Search code examples
pythonparsingvariablesstdoutreadlines

Can this be shortened / streamlined in any way?


I'm currently trying to learn Python and might still be doing things in too many steps/too bulky a way.

I got the following lines of code in one of my small programs and have been wondering if I could make it a bit more efficient?

stdin, stdout, stderr = ssh.exec_command('echo -e "MAIN\nnotifications\nsmtp\nstatus$" | confd-client.plx -batch')
orglines = stdout.readlines()
smtpstatus = int(orglines[20])
if smtpstatus == 1:
     do something
else:
     do something else

Example output from stdout looks as this:

['Available modes: MAIN OBJS RAW WIZARD.\n', 'Type mode name to switch mode.\n', "Typing 'help' will always give some help.\n", 'device_info$\n', 'limiting$\n', 'overlay@\n', 'reboot_reason%\n', 'recipients@\n', 'sender$\n', 'smtp\n', 'authentication$\n', 'password$\n', 'port$\n', 'server$\n', 'status$\n', 'tls$\n', 'username$\n', '1\n']

Basically, could I get the variable smtpstatus to be populated in a more efficient way from the stdout output here? I'm not sure if the fact that I have to convert it to an integer makes it a bit more complicated?

The 'field number' can vary from time to time, for this particular value it is 20 as you can see from the code snippet above.

Thanks in advance, Mike


Solution

  • Not really. Not by much anyway. Conversion to an int is a bit inefficient yes, since it has an exception handling overhead... but you could just compare smtpstatus == "1\n" as in comparing those two strings. But it wouldn't make that much of a difference. You could also consider to only read stdout up to the 20th line, if you don't need the rest. That's probably the biggest slowdown.