如何在subprocess模块中使用列表索引?

3

我没有太多使用Python的经验,仍在学习中。基本上,我有一个与特定工作相关的ID列表。目前,我只想能够通过列表中的第一个ID(使用a [0])并打印请求到hello.txt的输出。因此,整个命令本身将看起来像bjobs -l 000001 > hello.txt。完成后,我可以遍历整个ID文件,为每个命令输出创建单独的文件。

#! /usr/bin/python

import subprocess

a = [ln.rstrip() for ln in open('file1')]

subprocess.call(["bjobs -l ", a[0], "> hello.txt"], shell=True)

非常感谢您的帮助!如果我有任何表述不清楚的地方,请您提出来,我会尽力解释。


bjobs 应该做什么?在 Python 中,也不需要重定向输出,您可以将其写入文件。您能展示一下 file1 的样子吗? - Rik Poggi
Bjobs是我们自己的内部命令之一,基本上它只是打印有关作业的信息。File1只是一个ID列表-423720 424323 436617 439917 461407 461414 461475 462667 445113 445028 446471 450001 451030 457610 457613 457733 457852 459224 - ashleh
你是在问如何将子进程的输出重定向到文件吗? - bereal
2个回答

3

如果您只想获取第一个id,那么请按照以下方式操作:

with open('file1') as f:
    first_id = next(f).strip()
with语句将打开文件并确保关闭它。
然后你可以使用类似下面的方式获取bjobs输出:
output = subprocess.check_output(["bjobs", "-l", first_id], shell=True)

并写:

with open('hello.txt', 'wb') as f:
    f.write(output)

我建议分开获取和写入bjobs输出的过程,因为你可能想对其进行某些操作或者你可能会用Python编写bjobs。这将使事情保持独立。
如果你想循环遍历所有的id,可以这样做:
with open('file1') as f:
    for line in f:
        line = line.strip()
        # ...

如果您需要行号,可以使用enumerate

with open('file1') as f:
    for i, line in enumerate(f):
        line = line.strip()
        # ...

我知道我有点超前于你的要求,但是看起来你开始构建一些东西,所以我觉得这可能会有用。


1
这个文件怎么样,它的名字是spam.py:
with open('file1') as f:
  for line in f:
    subprocess.call([ 'bjobs', '-l', line.rstrip() ])

然后使用python spam.py > hello.txt来调用它。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接