Jump to content

Script working in Python 2.5 and 2.7 doens't when called with labpython


Recommended Posts

Hi All,

I'm trying to get some script running in labpython.

the code is the follwing

 

=====================

import socket
 
class tcpalinks :
    
    def __init__(self) :
        self.linkslist={}
        print("TCPALINK Init")
 
    def gettcpalink(self, visatring = ""):
        if visatring not in self.linkslist :
            sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
            sock.connect((visatring.split("::")[1],int(visatring.split("::")[2])))
            print("build connection: %s"%(visatring))
            self.linkslist[visatring] = sock
            
        else : 
            print("connection already exist %s"%(visatring))
        return self.linkslist[visatring]
 
 
    def tcpalinkcloseall(self) :
        for sockname in self.linkslist :
            self.linkslist[sockname].close()
 
class tcpalink :
 
      def __init__(self,sock) :
            self.currentsock=sock
          
      def tcpaquery(self, message) :
           self.currentsock.send(message+'''\r\n''')
           reply=self.currentsock.recv(1024)
           return reply
    
                
 
 
 
listoflinks = tcpalinks()
 
currentlink = tcpalink(listoflinks.gettcpalink("TCPIP0::127.0.0.1::41000::SOCKET"))
 
currentlink.tcpaquery("stop 1")
listoflinks.tcpalinkcloseall()
 
 

=====================

 

The code works perfectly when called from python25.exe or 27 but when called through the Labpython interface fails claining "socket" is not defined.

I'm pretty sure the instruction is sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM) but I can't understand why.

 

 

===================

Error 1050 occurred at PYTHON Execute Script__ogtk.vi->PYTHON sandbox.vi:<type 'exceptions.NameError'>, global name 'socket' is not defined
 
Possible reason(s):
 
LabVIEW:  Error occurred while executing script.

PYTHON Execute Script__ogtk.vi->PYTHON sandbox.vi:<type 'exceptions.NameError'>, global name 'socket' is not defined

===================

 

Any suggestion would be more than welcome.

The same instruction works fine when called directly and not inside the tcpalinks tcpalinks.

 

Best Regards

Filippo

 

 

 

 

 

Link to comment
I agree globalizing everything could be viable, altough ugly, workaround. 
The other solution I have in mind may be calling pyhon directly form the command line. This will obviously impair a lot my ability to move data back and forth but I really don't need it that much. 
What I'm working on is something like this https://dl.dropboxusercontent.com/u/13519740/TCPA%20Automation%20Engine.mp4 where the macro is recorded directly in python.
Running in the command line may help avoiding ugly issues when the python code has obvious hang up like (while 1 ... ) and the Vi hangs up as well.
 
Best Regards
Filippo

P.S. Using LabVIEW 2015 Labpython 4.0.0.4  Python 2.5 (and 2.7)

Link to comment

The problem is that when Python is started it determines its home path from a number of possible values and then determines the sys.path value from that. This is then used to find modules that you "import" in a script.

 

It does among other things check values like the PYTHONPATH and PYTHONHOME environment variable, registry entries and finally if that all doesn't lead anywhere the current executables directory. From there it tries to find the Lib directory inside the determined home path.

 

However I just installed Python 2.7.11 from the Python site on my machine and I don't see any environment variable nor registry entry for Python. That forces the Python DLL to rely on two remaining parameters, all of which don't help either. First the location of the Python DLL which has been moved from the Python directory to the Windows system directory in the past, so no way for Python to find out where it got installed, and then as last resort the executable directory, which is the LabVIEW installation directory; no joy to find the Python lib directory from there either. For the Python executable this last one is which saves the butt when running from within the Python console, but leaves any application that embeds the Python DLL in the cold.

 

Possible Workarounds:

 

1) append the relevant Lib path to the sys.path variable before your import statement (something like sys.path.append("C:\Python27\Lib")

2) Define PYTHONPATH=C:\Python27\Lib;<other possible module directories> or PYTHONHOME=C:\Python27 environment variable

3) Create a registry key HKLM\Software\Python\PythonCore\<version>\PythonPath\<name>" with the value of the Lib path

4) NOT RECOMMENDED: the default sys.path Python uses when everything else fails is a list of relative paths which would resolve to the so called Current Working Directory. This can be set with a call to the SetCurrentDirectory() Win32 API. Setting this to the Python Home path would theoretically work, except that this path is also modified by various other Windows functions, most noticably the File Dialog box, so using it as a runtime reference is a very brittle solutions.

 

Seems like there is actually infrastructure in the Python DLL to work with that, but that the standard installer forgets to set any of the possible values to help this infrastructure to do its work. There is no good way to remedy that from within LabPython itself since it shouldn't inherently know about Python installation specific details.

Link to comment

Wonderful and clear explanation. Adding sys.path.append("C:\Python27\Lib") is perfectly doable for me. I'll try it out.

 

Although I must say the python 2.7 is not working properly (2.5 works fine).
When I try to set the python27.dll in sys.32 as the server executor for labpython I get errors and if I insist in runnin a script I end up hanging all the labview processes leading to a forced kill with taskman.

I have a doubt this is due to the OS (unfortunately Win 8.1) but I cannot change it (IT rules). 

 

Anyway all this venture in python is due to my stubborn idea depicted in the video of "recording Vi Macros" ...

I'm already able to do so but the macro script is not a full featured language, the next improvement I want to do is record the marco in a proper programming  language in order to have access to nice statement like "for, while, if, case ....." python ended up to be a nice choice as a scripting language.

 

Best Regards

Filippo

Link to comment

Wonderful and clear explanation. Adding sys.path.append("C:\Python27\Lib") is perfectly doable for me. I'll try it out.

 

Although I must say the python 2.7 is not working properly (2.5 works fine).

When I try to set the python27.dll in sys.32 as the server executor for labpython I get errors and if I insist in runnin a script I end up hanging all the labview processes leading to a forced kill with taskman.

I have a doubt this is due to the OS (unfortunately Win 8.1) but I cannot change it (IT rules). 

 

You should probably not attempt to set the absolute path to the Python27.dll when it was installed in System32 (or more likely SysWow64 as in my case when installing the Python 2.7.11 version from Python.org). In that case just specifying Python27.dll alone should be safer.

 

Also note that the LabPython 4.0.something package that gets installed from VIPM is not compatible with Python 2.7. They changed various things in 2.7 in preparation for 3.x including removing some symbols from the DLL and then the LabPython initialization fails because it can't link to the expected symbols. I have prepared some fixes to the current LabPython code that conditionally links at initialization time to the correct symbols but haven't found time to properly build a new VIPM package for this.

Link to comment

Also note that the LabPython 4.0.something package that gets installed from VIPM is not compatible with Python 2.7. They changed various things in 2.7 in preparation for 3.x including removing some symbols from the DLL and then the LabPython initialization fails because it can't link to the expected symbols. I have prepared some fixes to the current LabPython code that conditionally links at initialization time to the correct symbols but haven't found time to properly build a new VIPM package for this.

Hmmm, that's odd because I'm running Python 2.7.10 and 2.7.11 with LabPython VIPM packages just fine when I installed Python from Python.org, installing the same versions from Ananconda tended to cause LabVIEW to crash, but I had been assuming that was something to do with which version of Visual Studio had been used to build the two sets of binaries.

 

Do the changes you've made in the LabPython codebase potentially allow Python 3.x to be used, or is goign to continue to be just a Python 2.x thing ? In the ideal world, I guess one might replace LabPython with something that looked more like an ipython/juypter client that could talk to juypter kernels to allow multithreaded LabVIEW to play with non-threadsafe Python modules. But in the ideal world, I'd have the time to look at trying to do that... :)

Link to comment

Hmmm, that's odd because I'm running Python 2.7.10 and 2.7.11 with LabPython VIPM packages just fine when I installed Python from Python.org, installing the same versions from Ananconda tended to cause LabVIEW to crash, but I had been assuming that was something to do with which version of Visual Studio had been used to build the two sets of binaries.

 

Do the changes you've made in the LabPython codebase potentially allow Python 3.x to be used, or is goign to continue to be just a Python 2.x thing ? In the ideal world, I guess one might replace LabPython with something that looked more like an ipython/juypter client that could talk to juypter kernels to allow multithreaded LabVIEW to play with non-threadsafe Python modules. But in the ideal world, I'd have the time to look at trying to do that... :)

 

It's a first step towards 3.0 compatibility but by far not enough. 3.0 changed a lot of things. As to running LabPython 4.0 with Python 2.7 I guess that thanks to the runtime dynamic linking, it may work fine as long as you don't hit code paths that depend on the symbols that changed in 2.7. And that is in fact something that makes me wonder if the dynamic linking is a good idea  :D.

 

Different Visual Studio versions might certainly have some influence. I'm not sure anymore if there are any resources that are shared across the Python-LabPython boundary but that would be totally problematic for sure if the Visual Studio and therefore the C runtime library versions differ.

Link to comment

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

By using this site, you agree to our Terms of Use.