I am using python 3.5.
I want to import some modules:
One, with some constants, for example:
m.constant1 = 2,3
m.constant2 = 4,5
Another one with some functions definitions, for example:
def b_initialize (model,i) :
return m.binit
And the use this information in my main program,
how can I do it??
Thanks in advance,
Michael
In the first lines of your program, write import m
and to access constant1 and constant2, you can write m.constant1 and m.constant2
Alternatively, in the beginning you can write from m import constant1, constant2. From then on, you can access the constant1 and constant2 just by writing their names, without the m.
As for the function definitions, I can't help you if I don't know the module name, but you if you do, just write modulename.functionname.
This is used very commonly and has most likely been asked and answered on the internet before, though, so make sure to search thoroughly before asking on Stack Overflow.
Related
My question is that just like in C Language we define macros as:
define pi=3.14
so i want to inquire is there a way in python also that we can define here..
right now i am directly assigning values to the variables at the start of my program like pi=3.14
and use 'pi' everywhere instead of 3.14..although it is working fine until now..but is there a concept of preprocessor directives or MACROS in python also..if yes then how can we define it?
i have directly used a variable like route_Head_len=8
and used it in the functions where i want this value 8
i am getting the results which i want..`routeHead_len=8
def readRouteHead():
route_Head=[]
for i in range(routeHead_len):
route_Head.append(data[i])
return route_Head
a=readRouteHead()
print("Route Head: ",a)`
Aplogies if I have the terminology all wrong; I am still learning the basics of Python. I have been unable to google this issue, probably in large part because I don't know the terminology..
So. I have built a class within a .py script with LOTS of methods/functions. To keep this remotely simple, I want to call these from a commandline argument. I have no idea how to explain it, and I can't find anhy examples, so I will try to demo it:
Take for example mute_on as the function that I want to call. I run the script with the function/method in the argument, like:
python3 ./myscript.py mute_on
I assume we'd import sys(?), define the class and the function, and create the relevant object from the class:
import sys
class TelnetAVR(PioneerDevice):
def mute_on(self, mute):
self.telnet_command("MO")
mypioneer = PioneerDevice('Pioneer AVR', '192.168.2.89', 8102, 10)
...and lastly I would like the commandline argument to call the method/function - instead of calling it explicitly like:
mypioneer.mute_volume()
..I want to use the arg (sys.argv[1]) to dynamically call the function, like:
mypioneer.{sys.argv[1]}()
Any ideas, kind people? I have been auto-referred to What is getattr() exactly and how do I use it? but I have no idea how that information can help me here.
I have tried setting cmnd = 'turn_off' and then the following failed...;
getattr(mypioneer, str(cmnd))
getattr(mypioneer, cmnd)
Thanks!
This answer seems a little basic, but I cannot complain as to its efficacy;
mypioneer = PioneerDevice('Pioneer AVR', '192.168.2.89', 8102, 10)
exp = 'mypioneer.' + sys.argv[1] + '()'
print('Executing: ' + exp )
exec(exp)
I gave up loking for a graceful answer, and simply constructed a string that I wanted to execute (exp) based on the commandline argument. Works great.. Home Assistant can use the same script to call 50 telnet controls over my Pioneer AVR.
I have a variable x, which has a string of 500 and more charhacters.
The problem is, it is very annoying when you do coding and this long string takes half of the screen.
My question is: is it possible to hide the value of variable, with out manipulating it's value? Open for any solution to solve problem. Thank you.
Its a little backwards of a solution but you can call X in a separate program and import it to your main program.
Importing variables from another file?
Here is a link to how to do that.
Another solution would be to call it at the top of your program and just type everything below it.
I have a complex class hierarchy which involves harnessing a wide array of OS commands to provide a uniform API to them in an automation library. Some of these commands are accessed via a cli interface, others via a rest based interface, and the classes therein have package names such as these:
cmd.interface.cli.mgmt
cmd.interface.cli.support
cmd.interface.rest
cmd.driver.cli.network_config
cmd.result.cli.network_config
cmd.driver.cli.stats
cmd.result.cli.stats
cmd.driver.rest.network_interface
cmd.result.rest.network_interface
etc, etc.
there are many of these, and they are all grouped logically and have a hierarchy of base classes, and they all contain a single class definition of basically the same name as the last file name in the package path.
i.e., an import statement and then "constructor" usage would look like this:
import cmd.driver.cli.network_config
.
.
.
config_driver = cmd.driver.cli.network_config.NetworkConfig(...)
I find the redundancy in this sort of class access to be really annoying, and it makes the code look kind of stupid.
Is there a good way to remove this naming redundancy while keeping the modules separate and intact?
Here are a few things I do not want to do to address this issue:
1.
from cmd.driver.cli.network_config import NetworkConfig as CliDriverNetworkConfig
from cmd.result.cli.network_config import NetworkConfig as CliResultNetworkConfig
from cmd.driver.rest.network_config import NetworkConfig as RestDriverNetworkConfig
(ugh!)
I don't want to pretend there is a cute name possible for each of these things. I really want to expose all the relevant information at time of use:
config_driver = cmd.driver.cli.network_config.NetworkConfig(...)
(but I really want, and this should be enough to make the code understandable:
config_driver = cmd.driver.cli.NetworkConfig(...)
)
put 30 or so of such class defs in cmd/driver/cli/__ init __.py
(also yucky)
in perl, this would be done in this manner:
use Cmd::Driver::CLI::Network_Config;
.
.
.
my $config_driver = Cmd::Driver::CLI::Network_Config->new(...);
is there any mechanism in python that would allow me to more succinctly call the constructor on these classes without the package name redundancy and without hiding important details of which class out of several with similar but reliably distinct full names is being called?
................................................
ADDITIONAL COMMENT at post + 1 hour:
It occurs to me that perl is also doing the same sort of thing, where the package is Cmd::Driver::CLI::Network_Config and the class method being called therein is 'new'. Thus the prettier look of the call in this case.
I guess if I name the module cmd.driver.cli.NetworkConfig and put a package scope method called 'new' which just calls cmd.driver.cli.NetworkConfig.NetworkConfig(...) I would get the same effect, such that I could then make the call:
import cmd.driver.cli.NetworkConfig
.
.
.
config_driver = cmd.driver.cli.NetworkConfig.new(...)
hmmmm... i realize that this may not be "pythonic" in several senses, and I don't like mucking about behind the scenes too much (this sort of thing is always a risk), but maybe this is the way to get what i want if i'm dead-set on it...
................................................
ADDITIONAL COMMENT at post + 1 week:
Gosh no up-votes even? Kind of a serious question. Perhaps I should not have said how I'd do this in perl... :-p Ah, well.
My proposition : uses __ import__ to define your function for instance.
def myInit(pathImport, *args):
t = __import__(pathImport+".network_config", globals(), locals(), [], 0)
return t.NetworkConfig(*args)
and use is
config_driver = myInit('cmd.driver.cli', ...)
Try something like this in your top level module or __init__.py:
# import submodules, exposing them to things that import this module directly
from cmd.interface.cli import mgmt
from cmd.interface.cli import support
from cmd.interface import rest
from cmd.driver.cli import stats as driver_stats
from cmd.result.cli import stats as result_stats
# hide unneeded variables from things that import this module (optional)
__all__ = ['mgmt', 'support', 'rest', 'driver_stats', 'result_stats']
This will expose the simplified names as module member variables to anything that references your root module. You can even do variations of this pattern at multiple levels of your hierarchy.
Lets say that there is a function in my Delphi app:
MsgBox
and there is a string which has MsgBox in it.
I know what most of you are going to say is that its possible, but I think it is possible because I opened the compiled exe(compiled using delphi XE2) using a Resource Editor, and that resource editor was built for Delphi. In that, I could see most of the code I wrote, as I wrote it. So since the variables names, function names etc aren't changed during compile, there should a way to execute the functions from a string, but how? Any help will be appreciated.
EDIT:
What I want to do is to create a simple interpreter/scripting engine. And this is how its supposed to work:
There are two files, scr.txt and arg.txt
scr.txt contains:
msg_show
0
arg.txt contains:
"Message"
And now let me explain what that 0 is:
First, scr.txt's first line is function name
second line tells that at which line its arguments are in the arg.txt, i.e 0 tells that "Message" is the argument for msg_show.
I hope my question is now clear.
I want to make a simple scripting engine.
In order to execute arbitrary code stored as text, you need a compiler or an interpreter. Either you need to write one yourself, or embed one that already exists. Realistically, the latter option is your best option. There are a number available but in my view it's hard to look past dwscript.
I think I've already solved my problem! The answer is in this question's first answer.
EDIT:
But with that, as for a workaround of the problem mentioned in first comment, I have a very easy solution.
You don't need to pass all the arguments/parameters to it. Just take my example:
You have two files, as mentioned in the question. Now you need to execute the files. It is as simple as that:
read the first line of scr.txt
check if it's a function. If not, skip the line
If yes, read the next line which tells the index where it's arguments are in arg.txt
pass on the index(an integer) to the "Call" function.
Now to the function which has to be executed, it should know how many arguments it needs. i.e 2
Lets say that the function is "Sum(a,b : integer)".It needs 2 arguments
Now let the function read the two arguments from arg.txt.
And its done!
I hope it will help you all.
And I can get some rep :)