Raj
Raj

Reputation: 374

Assign linux command output to variable in python 2.6.6

I am trying to port a shell script to python. Used various methods from google search, but none of them seems to work.

This is the shell command.

version=`awk '{print $5}' file_name | tr -d ")" `

These are the methods tried.

version = subprocess.call(['awk','{print $5}','file_name','|','tr','-d'], shell=True)
version = os.system("`awk '{print $5}' file_name | tr -d ")" `", shell=True)
version = commands.getstatusoutput(" awk '{print $5}' file_name | tr -d ")"  ")

Neither of the above commands worked. Could someone please help me with it.

Upvotes: 0

Views: 500

Answers (1)

Radovan Garabík
Radovan Garabík

Reputation: 143

Your examples have various quoting errors.

The most straightforward solution would be:

subprocess.call('awk \'{print $5}\' file_name | tr -d ")"', shell=True)

but that's not recommended, because file_name can contain spaces (you can get around by shell=False and proper use of list of arguments, but it's getting unreadable).

I'd suggest str.replace(')', '') insted of tr -d, and something likex.split()[4] for x in open('file_name') instead of awk, to get a pure python version.

Upvotes: 2

Related Questions