0

I have a python 2.7 numpy script which runs in the shell (it is python 2.7.13), but doesn't when run from a terminal or eclipse. Here's the code:

import numpy

def main():
    print numpy.__version__

When I run this from the python shell, I get this:

$ python
Python 2.7.13 (default, Sep  5 2017, 08:53:59) 
[GCC 7.1.1 20170622 (Red Hat 7.1.1-3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy
>>> print numpy.__version__
1.12.1
>>> 

When I try to execute the command in the terminal, I get this:

$ python simple_example.py
$ 

The code runs, but there are no import errors.

Can someone please help? This is driving me nuts! My $PYTHONPATH environment variable is below:

$ echo $PYTHONPATH
:/usr/lib/python27.zip:/usr/lib64/python2.7:/usr/lib64/python2.7/plat-
linux2:/usr/lib64/python2.7/lib-tk:/usr/lib64/python2.7/lib-
old:/usr/lib64/python2.7/lib-dynload:/usr/lib64/python2.7/site-
packages:/usr/lib64/python2.7/site-packages/gtk-
2.0:/usr/lib/python2.7/sitepackages:/usr/lib/python27.zip:
/usr/lib64/pytho
n2.7:/usr/lib64/python2.7/p
lat-linux2:/usr/lib64/python2.7/lib-tk:/usr/lib64/python2.7/lib-
old:/usr/lib64/python2.7/lib-dynload:/usr/lib64/python2.7/site-
packages:/usr/lib64/python2.7/site-packages/gtk-
2.0:/usr/lib/python2.7/site-packages

1 Answers1

0

Your program correctly outputs nothing.

I suspect that you think that main() will be implicitly called; it will not. If you want main() to run, you'll need to invoke it yourself. Conversely, if you have code that you want to run implicitly, don't put it inside a function defintion.

Try one of these:

import numpy

print numpy.__version__

or

import numpy

def main():
    print numpy.__version__

if __name__=="__main__":
    main()
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
  • The second example did it! Thanks Rob! My question now is why I'd need to add the snippet below main(). Any suggestions? – Anupam Banerji Nov 01 '17 at 01:22
  • I tried to explain that in my answer. `main()` is not automatically invoked. If you want `main()` to run, you'll have to invoke it yourself. – Robᵩ Nov 01 '17 at 01:56