Importing functions that require parameters

Peter Otten __peter__ at web.de
Mon Dec 10 08:49:14 EST 2007


Matt_D wrote:

>> import sys
>> import otp_encrypt
>> the_key = opt_encrypt.get_key(sys.argv[1])
>>
>> If that isn't what you want, you'll need to explain the sentence that
>> starts "Now I understand", with examples of what you have tried.
> 
> When I try:
> 
> from otp_encrypt import get_key
> 
> I get:
> 
> -----------------------------------------------
> IndexError                                Trace
> 
> C:\WINDOWS\system32\<ipython console> in <modul
> 
> Q:\python\my pys\otp_encrypt.py in <module>()
>      62         cipher += letter
>      63     return cipher
>      64
> ---> 65 print final(sys.argv[1])
>      66
> 
> IndexError: list index out of range
> 
> In [13]: from otp_encrypt import get_key()
> 
> I know why I'm getting the error -- I'm importing a function from a
> module in iPython with a sys.argv parameter. No big mystery there.

No you don't know -- you are trying to use a module that is meant to work
as a stand-alone script as a library. As a python module is executed when
it is imported, so is the print statement in line 65. To prohibit execution
of the script-only parts use an if-suite, e. g.:

def get_key(...):
   # ...

if __name__ == "__main__":
    print final(sys.argv[1])


Now the print statement will be executed if you invoke your script from
the command line

$ python otp_encrypt.py

but not by

import otp_encrypt

where the value of __name__ is "otp_encrypt".

Peter



More information about the Python-list mailing list