wDroter
wDroter

Reputation: 1249

glob files to use as input for a python script from a python script.

Instead of

cat $$dir/part* | ./testgen.py

I would like to glob the files and then use stdin for ./testgen.py while inside of my python script. How would i do this.

Upvotes: 1

Views: 1050

Answers (3)

tel
tel

Reputation: 13999

nneonneo is correct about shell expansion, but it won't work on Windows. Here's a simple, totally bulletproof cross-platform version:

import sys
from glob import glob

def argGlob(args=None):
    if args is None: args = sys.argv

    return [subglob for arg in args for subglob in glob(arg)]

argGlob will return the exact same thing as Unix-style shell expansion, and it also won't screw up any list of args that's already been expanded.

Upvotes: 0

Jon Clements
Jon Clements

Reputation: 142126

A combination of glob and fileinput could be used:

from glob import glob
import fileinput

for line in inputfile.input(glob('dir/part*')):
    print line # or whatever

Although if you get the shell to expand it - you can just use inputfile.input() and it will take input files from sys.argv[1:].

Upvotes: 0

nneonneo
nneonneo

Reputation: 179392

You could let the shell do it for you:

./testgen.py $$dir/part*

This passes every matching filename as a separate argument to your program. Then, you just read the filenames from sys.argv[1:].

Upvotes: 1

Related Questions