0

I have written a simple class "Test.py".

class Test():   
    def testMethod():
        print('Test method is executed')

I want to execute the method of the class from command prompt.

I am using following command for the same

python -c "from Test import testMethod; testMethod()"

I am getting following error

Traceback (most recent call last):
  File "<string>", line 1, in <module>
ImportError: cannot import name 'testMethod' from 'Test'

Can you please help me in identifying the issue in the command in an using

nascent
  • 117
  • 4
  • You need to make sure your `Test` class is available to be found at the level of command line execution. There are good answers on Python importing around SO, such as [this one](https://stackoverflow.com/questions/3987041/run-function-from-the-command-line) – MatBBastos Jun 01 '21 at 17:49
  • If, however, you aim at executing a specific function when running (not after importing) the script, you can make use of the `if __name__ == "__main__"` condition – MatBBastos Jun 01 '21 at 17:50

1 Answers1

1

By giving the class name to your Python file you might have just given yourself a bit of a headache to understand Python importing. You cannot import the class Test without referencing it to its file of origin. Now, to be able import the class (and, then, its methods), you need to first "tell" Python where the class is located. For my example, the file is named foo.py and is placed in ~/ directory

# foo.py

class Test():
    def test_method():
        print("Executed test method")

Then, you can run, from the same directory (~/), the following:

python -c "from foo import Test; Test.test_method()"

And your output should be:

>>> Executed test method
MatBBastos
  • 401
  • 4
  • 14
  • Thanks @MatBBastos for the solution. Yes I am able to get the desired output now. Since I am coming from Java background, I was expecting that class and file name should match. Do you have any good reference which explains the difference between the two in detail. – nascent Jun 02 '21 at 07:03
  • 1
    I see. In Python, you can have multiple classes in a single file, and the name of the file does not need to match any of them. Usually, the file is to be considered a 'module', that can have any arbitrary name, in which you can have classes (and its methods) and even functions without classes. – MatBBastos Jun 02 '21 at 12:32
  • 1
    When importing it is important to make sure Python can uniquely identify the element (class, method, function, attribute, etc) in the current environment. [PEP 8](https://www.python.org/dev/peps/pep-0008/#package-and-module-names) is the major reference for conventions in Python. If you look for packaging in Python, I found [this](https://towardsdatascience.com/how-to-build-your-first-python-package-6a00b02635c9) to be a nice starting reference. Besides, when talking Python, usually official docs are a good place to look. – MatBBastos Jun 02 '21 at 12:42