Reputation: 225
not used python much so still learning. Basically, I have a list of IDs which relate to a specific job. At the moment I just want to be able to pass the first ID in the list (using the a[0]) and print the output of the request to hello.txt. So the entire command itself is going to look like bjobs -l 000001 > hello.txt. Once I've got this done, I can loop through the entire file of IDs to create 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 haven't made myself clear on something then please ask and I'll try and explain.
Upvotes: 3
Views: 128
Reputation: 29302
If you want just the first id, do:
with open('file1') as f:
first_id = next(f).strip()
The with
statement will open the file and make sure to close it.
Then you could get the bjobs
output with something like:
output = subprocess.check_output(["bjobs", "-l", first_id], shell=True)
And write:
with open('hello.txt', 'wb') as f:
f.write(output)
I'm suggesting to separate the fetching and writing of the bjobs
output beacuse you might want to do something on it or maybe you'll write the bjobs
in Python so... Well this will keep things separated.
If you want to loop on all the ids, you can do it:
with open('file1') as f:
for line in f:
line = line.strip()
# ...
Or with enumerate
if you need the line number:
with open('file1') as f:
for i, line in enumerate(f):
line = line.strip()
# ...
I know that I went a little ahead of what you asked, but it seems like you're starting to build something, so I thought it might be useful.
Upvotes: 3
Reputation: 59426
How about this file, named spam.py
:
with open('file1') as f:
for line in f:
subprocess.call([ 'bjobs', '-l', line.rstrip() ])
Then call it using python spam.py > hello.txt
.
Upvotes: 1