re.compile() doesn't work under Windows?

John Machin sjmachin at lexicon.net
Thu Aug 31 17:07:34 EDT 2006


ddtl wrote:
> Hello everybody.
>
> My script uses re.compile() function, and while it rans without errors
> under Linux, when I ran that script under Windows I get the following
> error:
>
> Traceback (most recent call last):
>   File "C:\a\projects\re.py", line 4, in ?
>     import re
>   File "C:\a\projects\re.py", line 95, in ?
>     main()
>   File "C:\a\projects\re.py", line 37, in main
>     s_exp = re.compile(op['-s'])
> AttributeError: 'module' object has no attribute 'compile'
>
> What is the problem here? re module is installed and is on the path -
> for example, the following code works and doesn't cause any errors:
>
> import re
> re.compile('a')
>
> What else could cause such an error?

Change the name of your script file from re.py to
not_the_name_of_a_module.py -- you are importing your script, not the
re module. This is shown in the traceback: import re executes the
main() function in your script.

Worked on Linux? Maybe the script wasn't called re.py on Linux.
Alternatively:

(1) In Windows at least, the current directory is placed first on the
Python module search path. I would have expected the same to happen on
*x.

(2) Did you run it using an IDE on Linux? An IDE may fiddle with
sys.path.

Bottom line: however you ran it on Linux: insert
import sys
print "sys.path is", sys.path
at the top of your script and see what it produces. Note: '' (empty
string) means current directory.

Also it's a good idea to make scripts guard against inappropriate code
being executed when the script is imported (whether deliberately or
accidentally). The standard idiom is something like this:

if __name__ == "__main__": # being run as script, not imported
   def main():
        do_something()

HTH,
John




More information about the Python-list mailing list