0

I have a Python application that simulates the behaviour of a system, let's say a car.

The application defines a quite large set of variables, some corresponding to real world parameters (the remaining fuel volume, the car speed, etc.) and others related to the simulator internal mechanics which are of no interest to the user.

Everything works fine, but currently the user can have no interaction with the simulation whatsoever during its execution: she just sets simulation parameters, lauchs the simulation, and waits for its termination.

I'd like the user (i.e. not the creator of the application) to be able to write Python scripts, outside of the app, that could read/write the variables associated with the real world parameters (and only these variables).

For instance, at t=23s (this condition I know how to check for), I'd like to execute user script gasLeak.py, that reads the remaining fuel value and sets it to half its current value.

To sum up, how is it possible, from a Python main app, to execute user-written Python scripts that can access and modifiy only a pre-defined subset of the main script variables. In a perfect world, I'd also like that modifications applied to user scripts during the running of the app to be taken into account without having to restart said app (something along the reloading of a module).

Silverspur
  • 891
  • 1
  • 12
  • 33

2 Answers2

0

Make the user-written scripts read command-line arguments and print to stdout. Then you can call them with the subprocess module with the variables they need to know about as arguments and read their responses with subprocess.check_output.

Joe Iddon
  • 20,101
  • 7
  • 33
  • 54
0

One way to do this would be to encapsulate the application attributes in a class and make the variables that you want to keep concealed from the user "private", or rather pseudo-private, as Python does not have true access modifiers. You can effectively achieve variable privatization through use of underscores. See this post. The variables that are made "private" would not be accessible outside the class definition, so they would be hidden from your user script.

  • In the solution you suggest, the user scripts are executed 'inside' the application, just as the code in files written by the programmer, is this correct? – Silverspur Nov 09 '18 at 18:21
  • It doesn't matter where the user scripts are run from in my scenario. To anything external to the class where the private data is defined, the private data will be inaccessible. That would include other modules, other classes, and user-defined scripts that do not live within the class. – Channing Hurley Nov 09 '18 at 19:07