简体   繁体   English

如何在Python中从命令行控制持久对象

[英]How to control persistent object from command line in Python

I come from a Matlab background. 我来自Matlab背景。 In Matlab, one is able to create a persistent object (that persists in the 'workspace'), and then manipulate it from the command line. 在Matlab中,可以创建一个持久对象(在'workspace'中保留),然后从命令行操作它。 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? 我可以在Python中做这样的事情吗?

As far as I know something like than doesn't mean anything in python. 据我所知,python中没有任何意义。 Python doesn't have a concept like workspace. Python没有像工作空间这样的概念。 Python is an interpreter, it doesn't have anything to do with the IDE you are using. Python是一个解释器,它与您正在使用的IDE没有任何关系。

You may have an object that loads on program start and is saved on changes, look for python pickle module. 您可能有一个在程序启动时加载并保存在更改中的对象,查找python pickle模块。

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. 这会加载HOME环境变量。 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). 是的,你可以使用其中一个ipython发行版来做到这一点 :主要的是AnacondaCanopy (可能还有其他)。

You can also do that in a jupyter notebook environment. 您也可以在jupyter笔记本环境中执行此操作。

iPython preserves state of the variables; iPython保留变量的状态; these variables can be accessed, and manipulated further. 可以访问和操纵这些变量。

These distributions and environments are a great alternative to matlab in some cases. 在某些情况下,这些分布和环境是matlab的一个很好的替代方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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