[Baypiggies] importing variables into python namespace using argparse module

Abhishek Pratap abhishek.vit at gmail.com
Wed Sep 7 23:56:01 CEST 2011


Guys

I think I am stuck again while trying to open a file. It looks like a
type casting error but not sure.

##Error:
TypeError: coercing to Unicode: need string or buffer, list found


#code

def read_file(file):
    """Read the first same and create a dictionary
    """
    fh1 = open(file,'r')
    for line in fh1:
        print line


sam_file_1 = args.sam_file_1
sam_file_2 = args.sam_file_2

read_file(sam_file_1)


-Abhi


On Wed, Sep 7, 2011 at 2:01 PM, Abhishek Pratap <abhishek.vit at gmail.com> wrote:
> Thanks Simeon and Rami. Works now.
>
> -Abhi
>
>
>
>
> On Wed, Sep 7, 2011 at 1:55 PM, Rami Chowdhury <rami.chowdhury at gmail.com> wrote:
>> On Wed, Sep 7, 2011 at 21:11, Abhishek Pratap <abhishek.vit at gmail.com> wrote:
>>> This might sound naive as I am trying to learn python.
>>
>> Not at all, we've all been there :-)
>>
>>> I am using argparse to parse the command line arguments but I am not
>>> sure how they variables created by it are imported into python's
>>> current namespace for downstream usage.
>>
>> The simple answer is that they're not. I'll explain further after the
>> code sample
>>
>>> parser = argparse.ArgumentParser(description='Process some integers')
>>>
>>> parser.add_argument('--file_1', nargs=1 , type=file, required=True,
>>> help='Name of file 1')
>>> parser.add_argument('--file_2', nargs=1 , type=file, required=True,
>>> help='Name of file 2')
>>> parser.parse_args()
>>
>> Here, you need to capture the object that is returned from
>> parser.parse_args() -- that object is where any data captured by the
>> parser is stored, and you can access it from that object. So, for
>> instance:
>>
>>>>> args = parser.parse_args()
>>>>> print "File 1 is %s" % args.file_1
>>
>>> PS: Please let me know if this is not a appropriate forum to push such
>>> questions and if there are other mailing list that I could use coz in
>>> the coming days I am sure to send in a lot of email traffic.
>>
>> You could also try the main Python-language mailing list
>> (python-list at python.org) -- there are more people on the list and you
>> might get quicker responses to questions :-)
>>
>> Hope that helps,
>> Rami
>>
>> --
>> Rami Chowdhury
>> "Never assume malice when stupidity will suffice." -- Hanlon's Razor
>> +44-7581-430-517 / +1-408-597-7068 / +88-0189-245544
>>
>


More information about the Baypiggies mailing list