Import a custom python library

Typically: "How do I... ", "How can I... " questions
coppelia
Site Admin
Posts: 10747
Joined: 14 Dec 2012, 00:25

Re: Import a custom python library

Post by coppelia »

Code: Select all

#luaExec sim = require('sim')
#luaExec additionalPaths = {sim.getStringProperty(sim.handle_app, 'scenePath')}

from myModule import myFunction

def sysCall_init():
    sim = require('sim')
    print('starting')
    myFunction(sim)
In your myModule.py, e.g.:

Code: Select all

import datetime

def myFunction(sim):
    sim.addLog(sim.verbosity_scriptinfos, str(datetime.datetime.now()) + ' : Hello')
i.e. you need to pass the sim object as function argument.

Or maybe better like that:

Code: Select all

#luaExec sim = require('sim')
#luaExec additionalPaths = {sim.getStringProperty(sim.handle_app, 'scenePath')}

import myModule

def sysCall_init():
    sim = require('sim')
    print('starting')
    myModule.init(sim)
    myModule.myFunction()
and:

Code: Select all

import datetime

def init(a):
    global sim
    sim = a

def myFunction():
    global sim
    sim.addLog(sim.verbosity_scriptinfos, str(datetime.datetime.now()) + ' : Hello')
Cheers
javl0p
Posts: 25
Joined: 24 Mar 2023, 10:42

Re: Import a custom python library

Post by javl0p »

Ok, many thanks, it worked the following way

Code: Select all

#python
import sys
modulePath = 'C/:path/to/my/module/folder'
sys.path.append(modulePath)
and then calling the init function after declaring sim and simIK variables

Code: Select all

sim = require('sim')
simIK = require('simIK')

myModule.init(sim, simIK)
which is a bit cumbersome, but I guess is the only way to do it.

However, what I dont understand is why 'C:/path/to/my/module/folder' is not directly added by default, since I explicitely wrote that path in the 'usrset.txt' file
additionalPythonPath = 'C:/path/to/my/module/folder'
Shouldn't that option allow Coppelia to find all the .py script files in that folder?

Why do I have to add it manually in every child script?
coppelia
Site Admin
Posts: 10747
Joined: 14 Dec 2012, 00:25

Re: Import a custom python library

Post by coppelia »

Indeed...

you can pull lua and that should be resolved.

Cheers
javl0p
Posts: 25
Joined: 24 Mar 2023, 10:42

Re: Import a custom python library

Post by javl0p »

Ok, thanks for that commit.

But my company is stuck with CoppeliaPro v4.6 so I guess we can't have access to those last code changes...
coppelia
Site Admin
Posts: 10747
Joined: 14 Dec 2012, 00:25

Re: Import a custom python library

Post by coppelia »

Have a look at the last commit, you should be able to figure out the changes to make.

Cheers
javl0p
Posts: 25
Joined: 24 Mar 2023, 10:42

Re: Import a custom python library

Post by javl0p »

Ok, thank you!
Post Reply