What is the best way to invoke the os.system command and assign it to a variable without printing the output ?

Example :

ifName  = os.system('snmpwalk -v 1 -c <community> %s ifName.%s' % (switch,port))

Also with the output of the snmpwalk I will be wanting to only assign the last column. I know I could do with this with regex (re) but wondered what the most elegant way to achieve this was (i.e string formatting etc)...

Thanks,

Dani AI

Generated

os.system only returns the process exit code and leaves the command output on the terminal, so it can't be assigned to a variable. As hinted, the right approach is to capture stdout with subprocess (or avoid the shell entirely by using a dedicated SNMP library such as pysnmp). The examples below show safe, practical ways to run snmpwalk, capture its output, and extract whatever comes after the first colon on each line (handling optional quotes).

# Python 3 (3.5+)
import subprocess, re

cmd = ['snmpwalk', '-v', '1', '-c', community, switch, 'ifName.' + port]
proc = subprocess.run(cmd, capture_output=True, text=True, check=True)
for line in proc.stdout.splitlines():
    m = re.search(r':\s*(?:"([^"]*)"|(.*))$', line)
    if m:
        value = (m.group(1) or m.group(2)).strip()
        # value now holds the text after the colon, without surrounding quotes
# Python 2.7 (fallback)
import subprocess, re

cmd = ['snmpwalk', '-v', '1', '-c', community, switch, 'ifName.' + port]
try:
    out = subprocess.check_output(cmd)
except subprocess.CalledProcessError as e:
    out = e.output  # may contain partial output
for line in out.splitlines():
    m = re.search(r':\s*(?:"([^"]*)"|(.*))$', line)
    if m:
        value = (m.group(1) or m.group(2)).strip()

Notes and cautions:

  • Build the argument list (as shown) instead of a single shell string to avoid shell injection and quoting headaches. Avoid shell=True unless absolutely necessary.
  • Handle CalledProcessError to detect failures and inspect e.returncode / e.output.
  • If parsing SNMP program output is brittle for the project, switch to a native SNMP client library (pysnmp or similar) to get structured data instead of parsing text.

This approach follows 's suggestion to move away from os.system and gives a robust parsing alternative to string partitioning for quoted and unquoted values.

Recommended Answers

All 6 Replies

Use subprocess with Gribouillis Command class: http://www.daniweb.com/software-development/python/code/257449

For your extraction of last column I do not understand as you give no sample of output and what you want from that. The man page of Linux http://linux.die.net/man/1/snmpwalk gives example output like this:
sysDescr.0 = STRING: "SunOS 4.1.3_U1 1 sun4m"
sysObjectID.0 = OID: enterprises.hp.nm.hpsystem.10.1.1
sysUpTime.0 = Timeticks: (155274552) 17 days, 23:19:05
sysContact.0 = STRING: ""
sysName.0 = STRING: ""
sysLocation.0 = STRING: ""
sysServices.0 = INTEGER: 72

It has no columns.

Thanks Ill have a look at the lnk shortly. Relating to the column part, I may of worded it incorrectly.

Based on the output you added I would want to capture (as a variable) anything after the :.

Such as :
SunOS 4.1.3_U1 1 sun4m
(155274552) 17 days, 23:19:05

etc etc

Thanks for your help...

Partition is one way (split is another):

Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> data = """sysDescr.0 = STRING: "SunOS zeus.net.cmu.edu 4.1.3_U1 1 sun4m"
sysObjectID.0 = OID: enterprises.hp.nm.hpsystem.10.1.1
sysUpTime.0 = Timeticks: (155274552) 17 days, 23:19:05
sysContact.0 = STRING: ""
sysName.0 = STRING: "zeus.net.cmu.edu"
sysLocation.0 = STRING: ""
sysServices.0 = INTEGER: 72"""
>>> for info in data.splitlines():
        print info.partition(':')[-1]

        
 "SunOS zeus.net.cmu.edu 4.1.3_U1 1 sun4m"
 enterprises.hp.nm.hpsystem.10.1.1
 (155274552) 17 days, 23:19:05
 ""
 "zeus.net.cmu.edu"
 ""
 72
>>>

Is there not an easier way to get the output from a binary passed into a variable.
Seems like having to create a class etc etc seems pretty long winded.

Thanks,

Is there not an easier way to get the output from a binary passed into a variable.
Seems like having to create a class etc etc seems pretty long winded.

Thanks,

Output from a binary?

The binary being snmpwalk...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.