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}
python如何識別:在linux命令中使用os.popen?
我怎麼這麼糾正呢?
感謝,
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}
python如何識別:在linux命令中使用os.popen?
我怎麼這麼糾正呢?
感謝,
我會跳過外部流程乾脆:
with open("/home/xmp/distribution/sites.conf", "rt") as txtfile:
for line in txtfile:
fields = line.split(':')
print fields[0]
把所有這些都打開(「/ home/xmp/distribution/sites.conf」,「rt」)爲txtfile: for line in txtfile: fields = line.split(':') print fields [0] in一些變量?? – user3013012
如果您需要,您已經有了可以保存的字段值。 –
我不能清楚地看到你做了什麼,但似乎
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()
只是爲了澄清我在bash中執行命令的時間: cat /home/xmp/distribution/sites.conf|awk -F「:」'{print $ 1}' 它會從文件中取出第一個字段, 文件sites.conf似乎是這樣的:薩馬拉:10.141.110.4:10.141.110.20所以輸出: 將薩馬拉,所以我怎麼能在python與os.popen? – user3013012
@ user3013012正如我上面所寫的,字符串中的'''替換爲'\''。另一種方法是使用''「''樣式字符串:''」「cat /home/xmp/distribution/sites.conf|awk -F」:「'{print $ 1}'」「」'。 – glglgl
如果您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")
對我而言,這個建議非常好 – user3013012
mgmt_ip_1 = os。popen(「」「cat /home/xmp/distribution/sites.conf|awk -F」:「'{print $ 2}'」「」) MGMT_IP_1 = site_name.read()。replace('\ n',' ')爲什麼當我將它應用到二維場景時? – user3013012
在另一個評論中提供的'samara'示例適用於此 – damienfrancois
閱讀文件,並解析在'python'的字符串。沒有理由回到'awk'上。 –