TAGS :Viewed: 16 - Published at: a few seconds ago

[ Running Python on Windows from Shell ]

So I've got some script named 'some_class.py' located in the same folder as python.exe:

from __future__ import print_function

class some_class:
    def say_it(self):
    print('hello')

def main():
    instance = some_class()
    instance.say_it()

if __name__ == '__main__':
    main()

When I try running it with the following command while in Python Shell inside PowerShell:

some_class.py

I get:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'some_class' is not defined

Python's version is 3.4.1. What am I doing wrong?

Answer 1


You generally don't put your python programs into the folder you've installed python to -- that's not how it's supposed to be.

Also, python will not look into the directory of python.exe when looking for python modules, it looks into $PYTHONPATH (by default, into its library folders) and into the current working directory (which is the directory you were in when you called python.exe, not where python.exe itself lies.

You'll also have to import your file if you want to use things from it, so when in an interactive shell, you'd probably do

import my_python_file

I think you should go back to python.org and read the tutorial from start to end. It has a nice section on working with files, what modules actually are and how to use functionality from other files.

Answer 2


If you want to run it using the filename then don't start a python shell just python34 some_class.py from a cmd prompt. The if __name__ == '__main__': will mean the main() function will be run when the script is executed. If you import the script it will not be run, that is the point of using if __name__ == '__main__'