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

还没用过python,所以还在学习。 基本上,我有一个与特定工作有关的ID列表。 目前我只是想能够传递列表中的第一个ID(使用a [0]),并将请求的输出打印到hello.txt。 所以整个命令本身将看起来像bjobs -l 000001> hello.txt。 一旦我完成了这个工作,我可以遍历整个ID文件,为每个命令输出创build一个单独的文件。

#! /usr/bin/python import subprocess a = [ln.rstrip() for ln in open('file1')] subprocess.call(["bjobs -l ", a[0], "> hello.txt"], shell=True) 

任何帮助,将不胜感激! 如果我没有明确表示什么,那么请问,我会尽力解释。

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

我知道,我已经提前一点点了,但似乎你正在开始建立一些东西,所以我认为它可能是有用的。

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

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

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