python - 从 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
中。
有什么我想念的吗?
解决方案
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.
推荐阅读
- angular - 将布尔变量传递到路由器出口
- javascript - localhost:3000 de app.get 中的 JavaScript 问题
- ruby-on-rails - 未定义的局部变量或方法`cache_key_for_vendor_products'
- ruby-on-rails - 如何在 redmine 插件中调用 redirect_to
- javascript - 如何在 Angularfire Ionic 的单独页面中显示 Firebase 详细信息 [已回答]
- rust - 如何将计算 9 位位掩码中的个数的 C 函数转换为 Rust?
- python - 如何将具有多个分隔符的 df 列拆分为不同的列?
- android - recyclerview 内的 RecyclerView 只显示父 recyclerview 的最后一项
- assembly - 使用天然气进行进口的正确方法
- reactjs - XML5632:只允许一个根元素 - Microsoft 加载项