输出为Python中的列表

时间:2016-03-16 05:51:34

标签: python

我有一个名为localhosts的文件,它是

vagrant1 ansible_ssh_host=127.0.0.1 ansible_ssh_port=2200
vagrant2 ansible_ssh_host=127.0.0.1 ansible_ssh_port=2200
vagrant3 ansible_ssh_host=127.0.0.1 ansible_ssh_port=2200
vagrant4 ansible_ssh_host=127.0.0.1 ansible_ssh_port=2200
vagrant5 ansible_ssh_host=127.0.0.1 ansible_ssh_port=2200
vagrant6 ansible_ssh_host=127.0.0.1 ansible_ssh_port=2200
vagrant7 ansible_ssh_host=127.0.0.1 ansible_ssh_port=2200

并且,我希望在python中使用cat localhosts并将输出放在如下面的列表中

MACHINE = ['vagrant1', 'vagrant2', 'vagrant3', 'vagrant4',
           'vagrant5','vagrant6','vagrant7'].

到目前为止,我有

import os
os.system("cat localhosts")

我该怎么做?我想找到办法做到这一点。

4 个答案:

答案 0 :(得分:2)

你可以这样做:

>>> with open('file.txt') as f:
...     MACHINE = [line.split()[0] for line in f]
... 
>>> MACHINE
['vagrant1', 'vagrant2', 'vagrant3', 'vagrant4', 'vagrant5', 'vagrant6', 'vagrant7']

如果必须模拟Linux命令:

>>> MACHINE = subprocess.check_output(['cut', '-d ', '-f1', 'file.txt']).split()

>>> MACHINE
[b'vagrant1', b'vagrant2', b'vagrant3', b'vagrant4', b'vagrant5', b'vagrant6', b'vagrant7']

我在这里:

cut -d' ' -f1 file.txt

答案 1 :(得分:1)

试试这个

os.system只将命令运行到python脚本中。但是你想要将linux命令结果存储到变量中的问题。因此,请尝试使用commandssubprocess

#!/usr/bin/python
import commands
import re
filename = "input.txt"


extract  = (commands.getstatusoutput("cat %s"%(filename)))[1].split("\n")

machine = []
for i in extract:
    j = re.match("^(\w+)",i)
    machine.append(j.group(1))

print machine

答案 2 :(得分:1)

from subprocess import Popen, PIPE

machines_temp = Popen('cat localhosts', shell=True, bufsize=4096, stdout=PIPE).stdout.read().strip().split('\n')
machines = [x.split() for x in machines]
print([x[0] for x in machines])

这应该足够了

答案 3 :(得分:1)

import subprocess

catter = subprocess.Popen(['cat', 'localhost'], stdout=subprocess.PIPE)
cutter = subprocess.Popen(['cut', '-d', ' ', '-f1'], stdin=catter.stdout, stdout=subprocess.PIPE)
MACHINES = cutter.communicate()[0].split('\n')