子流程运行()在lis的所有元素上

2024-04-26 02:38:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个主机名/IP地址列表,我的脚本从文本文件中获取每个项目的名称,并将它们作为列表存储在nodes变量中。你知道吗

我想ping每个主机并将结果输出到文本文件。我可以用一个主机来完成,但是我很难理解如何遍历列表。你知道吗

我已经查看了Stackoverflow上的其他文章,但是大多数文章都使用OS模块,这已经被弃用了。你知道吗

我的代码:

#!/usr/local/bin/python3.6

import argparse
import subprocess


parser = argparse.ArgumentParser(description="Reads a file and pings hosts by line.")
parser.add_argument("filename")

args = parser.parse_args()

# Opens a text file that has the list of IP addresses or hostnames and puts
#them into a list.
with open(args.filename) as f:
    lines = f.readlines()
    nodes = [x.strip() for x in lines]

# Opens the ping program
ping = subprocess.run(
    ["ping", "-c 1", nodes[0]],
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE
)

# Captures stdout and puts into a text file.
with open('output.txt', 'w') as f:
    print(ping.stdout.decode(), file=f)
    f.close()

Tags: andimportparser列表stdout文章argparseargs
2条回答

只需像这样遍历节点列表:

for i in nodes:   
    ping = subprocess.run(
    ["ping", "-c 1", i],
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE)

希望有帮助:)

您可以直接遍历节点列表,如下所示:

with open(args.filename) as f:
    lines = f.readlines()
    nodes = [x.strip() for x in lines]

with open('output.txt', 'w') as f:
    for node in nodes:
        # Opens the ping program
        ping = subprocess.run(
            ["ping", "-c 1", node],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE
        )
        # Captures stdout and puts into a text file.
        print(ping.stdout.decode(), file=f)

请注意,您还可以直接迭代输入文件,这被认为比使用readlines()更“Pythonic”:

with open(args.filename,'r') as infile, open('output.txt', 'w') as outfile:
    for line in infile:
        node = line.strip()
        # Opens the ping program
        ping = subprocess.run(
            ["ping", "-c 1", node],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE
        )
    # Captures stdout and puts into a text file.
    print(ping.stdout.decode(), file=outfile)

请注意,这是未经测试的,但我看不到任何明显的错误。你知道吗

相关问题 更多 >