python如何识别:在linux命令中使用波本?

2024-04-19 19:19:21 发布

您现在位置: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}

那我怎么纠正呢?你知道吗

谢谢你


Tags: namehomereadosconfsitesitescat
3条回答

我会完全跳过外部过程:

with open("/home/xmp/distribution/sites.conf", "rt") as txtfile:
    for line in txtfile:
        fields = line.split(':')
        print fields[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()

如果您的awk脚本没有比这更复杂,那么您可能希望退回到其他地方提到的纯Python实现。你知道吗

否则,一个简单的解决方法是将最外层的'替换为"""

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

这应该可以工作,而不需要逃避最内部的'

作为旁注,cat在这里是无用的:

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

简化一下:

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

相关问题 更多 >