i have two script name is A.py and B.py
i want to know how to send value from A.py to B.py.
for more detail,when run finished A.py script at the end of script ,A.py call B.py.
my question is i have to send some value from A.py to B.py.
anybody some help me how to send value A.py to B.py,so i can use some value in B.py.
"Do I assume correctly that you want to have B.py to use all the variables with values
that exist when A.py finishes?"
this is what i want exactly. i was upload my A.py and B.py to pastebin site.
http://elca.pastebin.com/m618fa852 <- A.py
http://elca.pastebin.com/m50e7d527 <- B.py
i want to use B.py 's xx value, xx value is come from A.py .
sorry my english
Your question isn't quite clear.
import B
B.methodToExecute(argument)
Do I assume correctly that you want to have B.py to use all the variables with values that exist when A.py finishes?
[edit]
Ok, the problem is you cannot easily do this without any variable assignments. What you'd like to achieve is an import statement done backwards. Normally, if you import a module in an other module or script, the importer (in this example, A) can access the importee's (B) variables, methods etc., but not backwards.
In A.py:
a = 2
print "A.a:", a
import B
print "B.b:", B.b
from B import *
print "b in our namespace:", b
In B.py:
b = 3
This will print:
A.a: 2
B.b: 3
b in our namespace: 3
If you are 100% sure you want this (why wouldn't you create some related classes with methods, or just put the methods in one big module?), you can import module A from module B, so if you modify B.py:
In B.py:
b = 3
from A import *
print "a in B's namespace:", a
... and run it again, you'll see some weird output with double lines and the desired a in B's namespace: 2 line (so it's 50% success). The key is that if you are importing simple scripts without functions and/or module/class declaration, whenever Python imports something, the necessary objects and references will be created inside the Python VM and the imported script gets executed, so you can run into troubles with the previously done circular imports. Use modules or classes and you'll be better, because in those only the parts after
if __name__ == "__main__":
...
will be executed on import.
Or, another good idea in this thread is to call a subprocess, but then you need to check for the variables on the command line, not directly in your script's namespace.
Your question might have been phrased too abstractly for me to really know what you need.
Generally, what you would do is after you've done everything in A and are read for B, you will have import A at the top of your module and call a function in A that you what taking in all the values you want to pass. If B is currently using hard-coded globals you want to override, refactor it to use functions.
Related
So to keep it simple I just want to be able to reference the function in C from A and I'm not sure how to do this in python without directly referencing c which I don't want to do
a.py references b.py
b.py references c.py
c.py has a function in it called foo
I want to call foo from a.py but for abstraction purposes I want to only reference b.py
I tried to set up a simple example like the one above before I start attempting this on my actual codebase but it seems I can't see the member in C from A
So not the most ideal solution but it appears if I create a member for each sub file in b.py it will allow me to access it from a.py
It would look something like this
c.py
def call_me_c():
print("It works from c")
b.py
import c
cfile = c
a.py
import b
b.cfile.call_me_c()
It seems that entities imported using two different PYTHONPATHs are not the same objects.
I have encouneted a little problem in my code and I want to explain it with a little testcase.
I created the source tree:
a/
__init__.py
b/
__init__.py
example.py
in example.py:
class Example:
pass
and from the parent of folder a, I run python and this test:
>>> import sys
>>> sys.path.append("/home/marco/temp/a")
>>>
>>> import a.b.example as example1
>>> import b.example as example2
>>>
>>> example1.Example is example2.Example
False
So the question is: why the result is False? Even if imported by two different paths, the class is the same. This is a complete mess if the class is a custom exception and you try to catch it with except.
Tested with python 3.4.3
In Python the class statement is an executable statement, so each time you execute it you will create a new class.
When you import a module Python will check sys.modules to see whether a module at the specified path already exists. If it does then you will just get back the same module, if not it will try to load the module and execute the code it contains.
So two different paths to the same module will load the code twice, which executes the class statement twice and you get two independent classes defined.
This usually hits people when they have a file a.py which they run as a script and then in another module attempt to import a. The script is loaded as __main__ so has different classes and different global variables than the imported module.
The moral is, always be consistent in how you reference a module.
The is operator is used to check if two names are pointing to the same object (memory location).
example1.Example is example2.Example
are obviously not pointing at the same locations since you are importing the same object two times.
But, if you did something like:
a, b = example1.Example, example1.Example
a is b # True
Instead, you should use the == operator:
example1.Example == example2.Example
True
Note that if you don't implement __eq__or __hash__, the default behavior is the same as is
I'm confused about what happens if you tread a module as a singleton.
Say I have a module conf.py, that contains some configuration parameters which need to be accessed by multiple other files. In conf.py, I might have this piece of code (and nothing else):
myOption = 'foo' + 'bar'
If I now import it first in a.py, and then in b.py, my understanding is that the first time it is imported (in a.py), the string concatenation will be executed. But the second time it is imported (in b.py), conf.myOption already has its value, so no string concatenation will be executed. Is this correct?
If after doing these two imports, I then execute the following in b.py
conf.myOption = 'aDifferentFoobar'
then obviously b.py would now see this new value. Would a.py see the same value, or would it still see 'foobar'?
I believe (but correct me if I'm wrong) that imports are always referred to by reference, not by value? And I'm guessing that's what the above questions boil down to.
Try it and see:
mod.py:
def foo():
print("in foo()")
return "foo"
bar = foo()
opt = "initial"
b.py:
import mod
mod.opt = "changed"
a.py:
import mod
import b
print(mod.bar)
print(mod.opt)
Execute a.py:
$ python3.4 a.py
Output:
in foo()
foo
changed
We learn:
foo() is only executed once
mod.opt is changed by b.py
a.py sees the changed value of mod.opt
bonus: the order of imports in a.py does not matter
There is a strange behavior of isinstance if used in __main__ space.
Consider the following code
a.py:
class A(object):
pass
if __name__ == "__main__":
from b import B
b = B()
print(isinstance(b, A))
b.py
from a import A
class B(A):
pass
main.py
from a import A
from b import B
b = B()
print(isinstance(b, A))
When I run main.py, I get True, as expected, but when I run a.py, I am getting False. It looks like the name of A is getting the prefix __main__ there.
How can I get a consistent behavior?
I need this trick with import of B in a.py to run doctest on file a.py.
WSo what happens when you run a.py is that Python reads a.py and executes it. While doing so, it imports module b, which imports module a, but it does not reuse the definitions from parsing it earlier. So now you have two copies of the definitions inside a.py, known as modules __main__ and a and thus different __main__.A and a.A.
In general you should avoid importing modules that you are executing as well. Rather you can create a new file for running doctests and use something like
import a
import doctest
doctest.testmod(a)
and remove the __main__ part from module a.
Chain of events:
The a.py script is called.
The class A statement is executed, creating A in the __main__
namespace.
b is imported.
In b.py a is imported.
The class A statement is executed, creating A in the a namespace.
This A in the a namespace has no relation to the A in the
__main__ namespace other than having been generated by the same
code. They are different objects.
I agree with Helmut that it is best to avoid such circular imports. However, if you wish to fix your code with minimal changes, you could do the following:
Let's rename b.py --> bmodule.py so we can distinguish b the module from b the variable (hopefully in your real code these names are already distinct):
class A(object):
pass
if __name__ == "__main__":
import bmodule
b = bmodule.B()
print(isinstance(b, bmodule.A))
prints
True
I was reading the sourcode for a python project and came across the following line:
from couchexport.export import Format
(source: https://github.com/wbnigeria/couchexport/blob/master/couchexport/views.py#L1 )
I went over to couchexport/export.py to see what Format was (Class? Dict? something else?). Unfortunately Format isn't in that file. export.py does however import a Format from couchexport.models where there is a Format class (source: https://github.com/wbnigeria/couchexport/blob/master/couchexport/models.py#L11).
When I open up the original file in my IDE and have it look up the declaration, in line I mentioned at the start of this question, it leads directly to models.py.
What's going on? How can an import from one file (export.py) actually be an import from another file (models.py) without being explicitly stated?
If module a does a from b import Foo, then Foo is a member of a afterwards and accessible as a.Foo. It's only consequent that you can now import it too using from a import Foo.
This is commonly used if you have a large library distributed across multiple files and you want them to be accessible from a single location. Let's say you have a package foo with the following layout:
foo/
a.py
b.py
c.py
__init__.py
a.py, b.py, c.py, define the classes A, B and C, respectively.
If you wanted to use those classes, you'd normally have to write
from foo.a import A
from foo.b import B
from foo.c import C
This has at least two problems:
Much code (three lines) is needed for this simple import
The library author can now no longer change the file/class association afterwards, because that would break existing code.
So normally you just put the following in the __init__.py:
from a import A
from b import B
from c import C
Now you put all the pieces together in a single place and all of the classes are accessible with one import:
from foo import A,B,C