Global variable error inside tag change script

Hello,
I run this code successfully in the console script but when I try to run this tag change script I get this error: global name 'contents' is not defined
I define content as global inside my assign function but python doesn't understand it inside the tag change script.

from StringIO import StringIO
from ftplib import FTP
import system

ftp = FTP()
ftp.connect(ip, port)
ftp.login('','')
ftp.cwd('/LOGS/') 		
contents = ""
def assign(s):
	global contents
	contents += s + "\n"
ftp.retrlines("RETR " + filename, assign)

Move your code to a project library script. Call a function there from a one-liner in the gateway event. You are bumping into some really ancient legacy python scoping. Project library scripts always have sane python scoping. Note, this particular use of "scope" is, unfortunately, unrelated to they use of the word "scope" (Gateway, Vision, Designer, Perspective) anywhere else in Ignition.

3 Likes

I still get the error, when I move the code in the project lib and call it in my change tag script:

def getFTPfileCSV(ip, port, fileName, username = "", password = "", dir = '/LOGS/TICKETSR/'):

	from StringIO import StringIO
	from ftplib import FTP
	import system

	ftp = FTP()
	ftp.connect(ip, port)
	ftp.login(username, password)
	ftp.cwd(dir) 
	#ftp.retrlines('LIST')
	contents = ""

	def assign(s):
		global contents
		contents += s + "\n"
	
	ftp.retrlines("RETR " + fileName, assign)
	ftp.quit()

	return contents

I don't see global contents in your enclosing function.

Consider not using the global keyword at all. Instead, create an object at the top level that you can mutate to hold your persistent content. I usually use dictionaries or dictionary-like objects--you can assign and delete keys in them without needing the global keyword.

2 Likes