2024-04-19 19:19:21 发布
网友
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}
print SITE_NAME
":"
{print $1}
那我怎么纠正呢?你知道吗
谢谢你
我会完全跳过外部过程:
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(),那就更好了。你知道吗
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实现。你知道吗
awk
否则,一个简单的解决方法是将最外层的'替换为""":
"""
site_name = os.popen("""cat /home/xmp/distribution/sites.conf|awk -F ":" '{print $1}'""") SITE_NAME = site_name.read().replace('\n', '')
这应该可以工作,而不需要逃避最内部的'
作为旁注,cat在这里是无用的:
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")
我会完全跳过外部过程:
我看不清你做了什么,但似乎
绝对是错误的语法,所以它不应该运行。你知道吗
在字符串内部,
'
应该替换为\'
s如果您习惯于使用
subprocess
模块而不是os.popen()
,那就更好了。你知道吗更好的办法是
如果您的
awk
脚本没有比这更复杂,那么您可能希望退回到其他地方提到的纯Python实现。你知道吗否则,一个简单的解决方法是将最外层的
'
替换为"""
:这应该可以工作,而不需要逃避最内部的
'
作为旁注,
cat
在这里是无用的:简化一下:
相关问题 更多 >
编程相关推荐