首页 > 解决方案 > 从 perl 调用 python - 方法调用不正确

问题描述

我正在尝试从 Perl 脚本调用 python 脚本。python脚本导入另一个python文件。Perl 文件和 python 文件放在不同的目录中。当我尝试直接运行 python 脚本时,它会调用导入 python 文件的构造函数和导入文件的另一种方法并成功运行。但是,当我尝试从 Perl 脚本中执行相同操作时,调用了唯一的构造函数。

实用程序.py

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

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

运行.py

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

当我run.py直接运行时。输出将是第一个构造函数打印,然后是 hello 方法打印。当我试图从 Perl 脚本中调用它时python /app/python/run.py,唯一的构造函数是 print 而不是 hello 方法 print。

两个 python 目录都放在文件夹中/app/python,Perl 脚本出现在文件夹app/perl中。

有什么我想念的吗?

标签: pythonperl

解决方案


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.


推荐阅读