How do I use indexes on a list in a subprocess module?

not used by python, so it is still learning. Basically, I have a list of IDs that are specific to a particular job. For now, I just want to be able to pass the first id in the list (using [0]) and print the output of the request to hello.txt. Thus, the whole command will look like bjobs -l 000001> hello.txt. Once I do that, I can loop through the entire ids file to create a separate file for each command output.

#! /usr/bin/python

import subprocess

a = [ln.rstrip() for ln in open('file1')]["bjobs -l ", a[0], "> hello.txt"], shell=True)


Any help would be appreciated! If I have not clarified something, then ask and I will try and explain.


source to share

2 answers

If you only want the first identifier, do:

with open('file1') as f:
    first_id = next(f).strip()


The operator with

will open the file and be sure to close it.

Then you can get the output bjobs

with something like:

output = subprocess.check_output(["bjobs", "-l", first_id], shell=True)


And write:

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


I suggest separating fetching and writing the output of the bjobs

output you might want to do something, or maybe you write bjobs

in Python, so ... Well that will keep things separate.

If you want to iterate over all ids, you can do this:

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


Or with enumerate

if you want a line number:

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


I know I was a little ahead of what you asked, but it looks like you are starting to build something, so I thought it might be helpful.



How about this file named


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


Then call it with python > hello.txt




All Articles