Lenton
Lenton

Reputation: 519

How to put shell command line output to a variable on Ubuntu with Python 2.7

I use the id user command and I get user's info for example, I get output of uid=1000(user), gid=1000(user), groups=1000(user), 4(adm), 24(cdrom), 27(sudo), 30(dip), 46(pugdev), 113(lpadmin), 128(sambashare) What I wanna do is, somehow put each of the numbers into a different variable (or array) and then use them as variables, which later I would translate those numbers in program to words, so you could understand user's info, for example take the group's number and translate it to group number, take user id and translate it if it's admin or standard user etc.

Upvotes: 0

Views: 133

Answers (2)

Dumidu Handakumbura
Dumidu Handakumbura

Reputation: 426

It will be easier to parse the output of 'id' command from within python. you can pass the value from the shell into the python script using a command substitution like shown below,

PARAMETER="$(id user)"
python script.py $PARAMETER

then from the script, you can clean out the values doing something like(you may need to change this according to your exact requirement),

import sys

lst=list()
args=sys.argv[1:]
print args
for i in args:
    if '=' in i:
        lst.append(i[i.find('=')+1:i.find('(')])
    else:
        lst.append(i[:i.find('(')])



print lst

Upvotes: 0

John Zwinck
John Zwinck

Reputation: 249093

You don't need to use the shell to spawn id user and so on, because Python has a module for this: grp. See here: https://docs.python.org/2/library/grp.html

And for user info, pwd: https://docs.python.org/2/library/pwd.html

Upvotes: 1

Related Questions