You can tell the system that your hw.pyo
file is "executable", for example (in Linux, MacOSX, or any other Unix-y system) by executing the command chmod +w hw.pyo
at the terminal shell prompt. Consider, for example, the following short and simple shell session:
$ cat >hw.py
print('hello world')
$ python2.5 -O -c'import hw'
hello world
$ ./hw.pyo
bash: ./hw.pyo: Permission denied
$ chmod +x hw.pyo
$ ./hw.pyo
hello world
$
By default, .pyo
(and .pyc
) files are not marked as executable because they're mostly meant to be imported, not directly executed (indeed, note that we're explicitly using a Python import
statement to create the .pyo
file!); however, as this example shows, it's quite easy to make one of them "executable as the main script". BTW, observe also:
$ cat >hw.py
print('hello world from ' + __name__)
$ python2.5 -O -c'import hw'
hello world from hw
$ chmod +x hw.pyo
$ ./hw.pyo
hello world from __main__
$
The __name__
is what tells the module whether it's being import
ed (so the first "hello world" says "from hw
") or run as the main script (so the second one says "from __main__
"). That's the reason modules that are designed to be used both ways normally end with if __name__ == '__main__': main()
or the like, where main
is a function that, this way, gets called iff the module's running as the main script (it's always best to have all substantial code execute in a function, not at a module's top level).