Anshul Parashar
Anshul Parashar

Reputation: 3126

Calling python from perl - methods are not calling properly

I am trying to call python script from a Perl script. python script importing another python file. Perl file and python files are placed into different directories. When I am trying to run python script directly, it calls the constructor of import python file and another method of import file and working successfully. However, When I was trying to do the same from Perl script the only constructor is called.

Utility.py

Class DemoCheck :
   def Hello():
   print("Hello")

   Utility(self):
   print("Constructor calling")

run.py

import Utility
const = Utility.DemoCheck
const.Hello()

When I am running run.py directly. The output will be first constructor print then hello method print. When I am trying to call it from Perl script python /app/python/run.py the only constructor is print not hello method print.

Both python directories are placed into folder /app/python and Perl script present into folder app/perl.

Is there anything that I am missing?

Upvotes: 1

Views: 268

Answers (1)

amon
amon

Reputation: 57640

This is unrelated to Perl, and is entirely due to the directory from which you run your Python script.

When you import a Python module, the module is searched for in the directories listed in sys.path. This includes the location of the standard library, and the current directory. So everything works when you run from the directory that includes the Utility.py file.

Here, there are four sensible solutions you might apply:

  • Change the current directory to app/python before launching the Python script.

  • Add the location of your modules to the PYTHONPATH environment variable.

  • Better: Turn your Python script into a package that can be installed, and install it on your system, so that its modules are available from the locations where Python looks by default.

  • Even better: use relative imports so that the sys.path lookup is avoided entirely:

    from .Utility import DemoCheck
    #    ^--
    DemoCheck().Hello()
    

    However, that requires the two modules to have a parent package, i.e. be part of some __init__.py directory that was loaded first.

Upvotes: 1

Related Questions