Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing an argument to a python script and opening a file

Tags:

python

I've built a script that takes a filename as an argument and extracts all lines that match a certain pattern. Trouble is I can't open the filename - I keep getting :

"TypeError: coercing to unicode: need string or buffer"

It's complaining about the line info = open(name, 'r').

Here's the code:

import re
import sys
print sys.argv[1:]

keyword = 'queued='
pattern = re.compile(keyword)

name = sys.argv[1:]
inf = open(name, 'r') 
outf = open("test.txt", 'w')

for line in inf:
    if pattern.search(line):
        outf.write(line)

And I call it with

`extract.py trunc.log`

Any ideas what I'm doing wrong?

like image 407
BeeBand Avatar asked Aug 29 '12 12:08

BeeBand


2 Answers

sys.argv[1:] is a list, not a string. When you slice a list, you get a list back -- even if you only take 1 element with the slice. You need to give open a string. Perhaps you wanted sys.argv[-1] (the last element)?

As a side note, the python standard library provides commandline parsing options -- One is the excellent argparse module which was introduced in python 2.7, but can be installed with very minimal effort on older python versions (I use it with python2.6 regularly).

like image 114
mgilson Avatar answered Oct 11 '22 14:10

mgilson


This:

name = sys.argv[1:]

makes name into a list of all arguments except the first. You mean:

name = sys.argv[1]

For real-world usage, you might want to look into argparse.

like image 38
unwind Avatar answered Oct 11 '22 12:10

unwind