Import OS in script

Hello,

I am trying to use the os functions in my scripts to access the latest file from a folder. My code works perfectly fine when I run it on the script console but once I try to run it on the timer scripts I receive this error. Does anyone know what could be wrong? Can I not use os on timer scripts?

Keep in mind that the script console runs in client scope and the gateway scripts run in Gateway scope. This does have implications.

2 Likes

Your immediate problem is caused by gateway event scripts using legacy Python scoping rules in 8.1 and prior versions; this means the imports defined in the outer scope are not available inside the defined functions.
The correct solution to that problem is to move everything you're doing into the project script library, and make your gateway timer script a one-line call to someLibrary.someFunction(); the move into the project library will get you to regular scoping rules that make sense.

Your second problem is that Jython's standard library isn't great. You should import and use Java's standard library construct (e.g. in this case one of the static methods from Files); it will be faster, give you less inscrutable errors, and in general cause you less pain over time.

In other words, the order of preference for a maintainable script over time is:
0. Don't use a script :smile:

  1. Ignition's built in system library
  2. Java's standard library constructs via import, e.g. from java.x import y or import java.x.y
  3. "Well known" third party Java libraries, like Google Guava or Apache Collections, that Ignition includes in all scopes. These are technically subject to change, but in practice seldom do outside of major Ignition versions.
  4. In a distant last place, Jython standard library imports.

Note that only option 1 is within scope of our official support.

4 Likes