Python – How do I use indexes in a list in a subprocess module?

How do I use indexes in a list in a subprocess module?… here is a solution to the problem.

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

I

haven’t used Python much, so I’m still learning. Basically, I have a list of IDs related to a specific job. Currently I just want to pass the first ID in the list (using a[0]) and print the output of the request to hello.txt. So the whole command itself looks like bjobs -l 000001 > hello .txt. Once this is done, I can iterate through the entire ID file, creating a separate file for each command output.

#! /usr/bin/python

import subprocess

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

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

Any help would be appreciated! If I don’t make something clear, ask questions and I’ll try to explain.

Solution

If you only want the first ID, do the following:

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

The with statement opens the file and ensures that it is closed.

Then you can get bjobs output like this:

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

Then write:

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

I recommend separating the fetch and writing of the bjobs output, because you might want to do something on it, or you might write bjobs in Python so… Well, this will keep things apart.

If you want to iterate through all the IDs, you can do this:

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

Or enumerate with >enumerate if you need the line number:

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

I

know I was a little earlier than you asked, but it looks like you’re starting to build something, so I thought it might be useful.

Related Problems and Solutions