mrkn / pycall.rb

Calling Python functions from the Ruby language
MIT License
1.06k stars 75 forks source link

Importing a local module #68

Closed AndreaOrru closed 6 years ago

AndreaOrru commented 6 years ago

Is there a way to import modules from the local directory?

AndreaOrru commented 6 years ago

Answering my own question and for future reference for others: set your PYTHONPATH to the current directory and import normally.

mrkn commented 6 years ago

@AndreaOrru You can use PyCall.sys.path to manage module search path in runtime.

PyCall.sys.path.append File.dirname(__FILE__)
mod = PyCall.import_module('module_name')
MarieS1415 commented 5 years ago

Hello,

I have a SyntaxError when calling a local module, I wonder if it is not related to the import I am not doing correctly.

At the top of a model, I have the following code: require 'pycall/import' include PyCall::Import PyCall.sys.path.append File.dirname(Rails.root.join('lib', 'assets', 'cat', 'cat.py')) cat = PyCall.import_module('cat')

The file cat.py I am trying to call is: `import numpy as np

from catsim.selection import MaxInfoSelector from catsim.stopping import MinErrorStopper

def next_item() -> int: return 1

and the command PyCall.import_module('cat') creates the following error: PyCall::PyError: <type 'exceptions.SyntaxError'>: ('invalid syntax', ('/home/mar/Documents/Mar/stats-engine-api-v2/lib/assets/cat/cat.py', 6, 17, 'def next_item() -> int:\n'))

I am using python 3, and PyCall 1.0.3 (using a more recent version is not possible because it create segmentation faults, maybe because of sidekiq).

Thank you for your indications and advice.

MarieS1415 commented 5 years ago

As explained here: https://stackoverflow.com/questions/12732743/syntax-error-on-the-colon-in-an-if-statement, I think it might be because a bracket is not closed somewhere. @mrkn, would it be possible that it is in the import_module function of PyCall 1.0.3?