如何在子进程模块中使用列表中的索引?

2024-06-26 13:47:52 发布

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

还没怎么用,所以还在学。基本上,我有一个与特定工作相关的ID列表。目前,我只希望能够传递列表中的第一个ID(使用a[0]),并将请求的输出打印到你好.txt. 所以整个命令本身看起来就像bjobs-l 000001>;你好.txt. 完成后,我可以遍历整个IDs文件,为每个命令输出创建一个单独的文件。你知道吗

#! /usr/bin/python

import subprocess

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

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

任何帮助都将不胜感激!如果我在某些事情上没有说清楚,那么请问我,我会尽力解释的。你知道吗


Tags: 文件import命令gttxtidids列表
2条回答

这个名为spam.py的文件怎么样:

with open('file1') as f:
  for line in f:
    subprocess.call([ 'bjobs', '-l', line.rstrip() ])

然后使用python spam.py > hello.txt调用它。你知道吗

如果只需要第一个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()
        # ...

或者使用^{}如果需要行号:

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

我知道我有点超前于你的要求,但似乎你开始建立一些东西,所以我认为它可能是有用的。你知道吗

相关问题 更多 >