简体   繁体   中英

How to control persistent object from command line in Python

I come from a Matlab background. In Matlab, one is able to create a persistent object (that persists in the 'workspace'), and then manipulate it from the command line. In other words I can do something like this all from the command line:

myStatic.initiate() // myStatic is a static class that consists of static functions only; the initiate function would create the persistent object
myStatic.method1()
...
myStatic.stop() // Erasing the workspace

Would I be able to do something like this in Python?

As far as I know something like than doesn't mean anything in python. Python doesn't have a concept like workspace. Python is an interpreter, it doesn't have anything to do with the IDE you are using.

You may have an object that loads on program start and is saved on changes, look for python pickle module.

Save like this:

import pickle

favorite_color = { "lion": "yellow", "kitty": "red" }

pickle.dump( favorite_color, open( "save.p", "wb" ) )

And to load it:

favorite_color = pickle.load( open( "save.p", "rb" ) )
# favorite_color is now { "lion": "yellow", "kitty": "red" }

Or you may use environmental variables.

import os
print os.environ['HOME']

this loads the HOME environmental variable. This is a better solution in my opinion. But this way the scope limited to a user, and having multiple environments for a single user has it's own cons.

Yes, you can do that using one of the ipython distributions: the main ones are either Anaconda , or Canopy (there may be other).

You can also do that in a jupyter notebook environment.

iPython preserves state of the variables; these variables can be accessed, and manipulated further.

These distributions and environments are a great alternative to matlab in some cases.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM