embedded python : can't get or set a variable

ycollet at freesurf.fr ycollet at freesurf.fr
Tue Dec 26 07:43:32 EST 2006


Hello,

I'm trying to write a program to send python statements to a python
server via tcp and then get back results via a tcp connection. It
nearly works ... but I'm totally lost with the embedded dictionary (I'm
quite new to python).
The first part of the server start the python interpreter via
Py_Initialize() and then waits for python statements.
To send command, I get some strings and evaluate them through
PyRun_String.
To get value, I try to build a dictionary and get the result via
PyDictGetItem.
Here is a sum-up of the c++ python part:

Py_Initialize();
pDictionary = PyDict_New();

....

PyRun_String(PyCommand.str().c_str(),Py_file_input,pDictionary,pDictionary);

...

PyDict_SetItemString(pDictionary, "__name__", PyEval_GetBuiltins());
pResult = PyDict_GetItemString(pDictionary, "a");

...

if (!PyArg_Parse(pResult, "i", &intValue))
{
  cout << "tcp-server: wrong type" << endl;
}


When I send a statement, here is a log of the messages I get :

./tcp-client 2100 send a=15
Parameter 0 : ./tcp-client
Parameter 1 : 2100
Parameter 2 : send
Parameter 3 : a=15
line to send : send a=15
tcp-client: send or stop command
Quit: tcp-client
  connected to 127.0.0.1:45577
  --  send a=15
send command: line = a=15
Traceback (most recent call last):
  File "<string>", line 1, in ?
NameError: name 'a' is not defined
Waiting for TCP connection on port 2100 ...

When I get a statement, here is a log of the message I get:

Parameter 0 : ./tcp-client
Parameter 1 : 2100
Parameter 2 : get
Parameter 3 : a
line to send : get a
tcp-client: get command
  connected to 127.0.0.1:45578
  --  get a
get command - variable to get : a .
Dictionary size = 2
DEBUG: print a
print type(a )

DEBUG: pResult = 0x804fd08
DEBUG: pDictionary = 0xb7c44d74
Traceback (most recent call last):
  File "<string>", line 1, in ?
NameError: name 'a' is not defined
['__builtins__', '__doc__', '__name__']
DEBUG: intValue = 15
tcp-server: get = 15
tcp-client: result = 15
Quit: tcp-client

My question is: how to get a global variables via PyDict_* ?
Why does the python interpreter prints an error message when I send my
command "a=15" ?
Why does it finally accepts my command "a=15" ?

Your sincerely,

Yann COLLETTE




More information about the Python-list mailing list