sbinet / go-python

naive go bindings to the CPython2 C-API
Other
1.53k stars 139 forks source link

unsupport from .. import test #81

Closed ansjsun closed 5 years ago

ansjsun commented 5 years ago

it is a greate project for us , but

like this from .. import test not support

and no err info .

i usekeras some code write like this .

but it can not load python file , and not throw exception .

  1. if not fix code , how to support it
  2. how too get err when load python file err

thank`s

sbinet commented 5 years ago

I believe this C-API does what you want:

ie:

but you'll still have to do a getattr to get at the module element you want (ie: test in your example.)

that would work as well:

module := python.PyImport_ImportModule("pkga.pkgb")
if module == nil {
    panic("error")
}
defer module.DecRef()
attr := module.GetAttrString("test")
if attr == nil {
    panic("error")
}
defer attr.DecRef()

str := attr.Str()
if str == nil {
    panic("error")
}
defer str.DecRef()
fmt.Printf("test: %v\n", python.PyString_AS_STRING(str))

that's the equivalent of:

from pkga.pkgb import test
print("test: {}".format(test))
sbinet commented 5 years ago

feel free to reponen if something isn't clear.

ansjsun commented 5 years ago

@sbinet

like this

python

dir /home/workspace/t1.py /home/workspace/dir/main.py

t1.py

print "test12321312312"

main.py

import sys
from .. import test # here has err when load

print "hello "

go

sysModule := python.PyImport_ImportModule("sys")
path := sysModule.GetAttrString("path")
python.PyList_Insert(path, 0, PyStr("/home/workspace/dir"))
model = python.PyImport_ImportModule("main")
//now model is nil 
sbinet commented 5 years ago

ah. well, on my box, with python2:

$> tree .
.
├── dir
│   └── main.py
└── t1.py

1 directory, 2 files

$> cd dir
$> python2
Python 2.7.16 (default, Mar 11 2019, 18:59:25) 
[GCC 8.2.1 20181127] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import main
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "main.py", line 2, in <module>
    from .. import test
ValueError: Attempted relative import in non-package
>>>