python如何识别:在linux命令中使用os.popen?

时间:2013-11-20 12:19:23

标签: python

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

当我正在print SITE_NAME时,它会向我显示文件中写入的整个数据但无法识别":"{print $1}

所以我怎么纠正这个?

谢谢,

3 个答案:

答案 0 :(得分:1)

我会完全跳过外部流程:

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

答案 1 :(得分:1)

如果您的awk脚本并不复杂,那么您可能希望依赖其他地方提到的纯Python实现。

否则,一个简单的解决方法就是用[{1}}替换最外面的'

"""

这应该可以在不需要逃避最内层site_name = os.popen("""cat /home/xmp/distribution/sites.conf|awk -F ":" '{print $1}'""") SITE_NAME = site_name.read().replace('\n', '') s

的情况下工作

作为旁注,'在这里没用:

cat

并简化一下:

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

答案 2 :(得分:0)

我无法清楚地看到你做了什么,但似乎

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

语法肯定是错误的,所以根本不应该运行。

在字符串中,'应替换为\' s。

如果您习惯使用subprocess模块而不是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()

更好的做法是

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()