user3013012
user3013012

Reputation: 29

How can python recognize : in linux command using os.popen?

site_name = os.popen('cat /home/xmp/distribution/sites.conf|awk -F ":" '{print $1}'')
SITE_NAME = site_name.read().replace('\n', '')

when I'm doing print SITE_NAME it shows me the whole data written in file and does not recognize ":" and {print $1}

so how i correct this?

thanks,

Upvotes: 0

Views: 139

Answers (3)

damienfrancois
damienfrancois

Reputation: 59260

If your awk script is not more complex than that, you might want to fall back on a pure Python implementation as mentioned elsewhere.

Otherwise, an easy fix is to replace the outer-most ' with """ :

site_name = os.popen("""cat /home/xmp/distribution/sites.conf|awk -F ":" '{print $1}'""")
SITE_NAME = site_name.read().replace('\n', '')

This should work without the need to escape the inner-most 's

As a side note, catis useless here:

site_name = os.popen("""awk -F ":" '{print $1}' /home/xmp/distribution/sites.conf""")

and to simplify a bit:

site_name = os.popen("awk -F ':' '{print $1}' /home/xmp/distribution/sites.conf")

Upvotes: 1

Steve Barnes
Steve Barnes

Reputation: 28405

I would skip the external processes altogether:

with open("/home/xmp/distribution/sites.conf", "rt") as txtfile:
    for line in txtfile:
        fields = line.split(':')
        print fields[0]

Upvotes: 1

glglgl
glglgl

Reputation: 91119

I cannot clearly see what you did, but it seems that

os.popen('cat /home/xmp/distribution/sites.conf|awk -F ":" '{print $1}'')

is definitely wrong syntax, so it shouldn't run at all.

Inside the string, the 's should be replaced with \'s.

Even better it would be if you would get used to using the subprocess module instead of os.popen().

import subprocess
sp = subprocess.Popen('cat /home/xmp/distribution/sites.conf|awk -F ":" \'{print $1}'\', shell=True, stdout=subprocess.PIPE)
SITE_NAME = sp.stdout.read().replace('\n', '')
sp.wait()

Even better would be to do

with open("/home/xmp/distribution/sites.conf", "r") as txtfile:
    sp = subprocess.Popen(['awk', '-F', ':', '{print $1}'], stdin=txtfile, stdout=subprocess.PIPE)
    SITE_NAME = sp.stdout.read().replace('\n', '')
    sp.wait()

Upvotes: 0

Related Questions