Python: read and execute lines from other script (or copy them in)?
Consider a python script:
####
#Do some stuff#
####
#Do stuff from separate file
####
#Do other stuff
What it the best way to implement the middle bit (do stuff that is defined in another file)? I've been told that in C++ there's a command that can achieve what I'm looking to do. Is there an equivalent in Python?
eg if A.py is:
print 'a'
### import contents of other file here
print 'm'
and B.py is:
print 'b'
print 'c'
print 'd'
then the desired output of A.py is:
a
b
c
d
m
B.py won't actually contain print statements, rather variable assignments and simple flow control that won't conflict with anything declared or defined in A.py. I understand that I could put the contents of B.py into a function, import this into A.py and call this function at the desired place. That would be fine if I wanted the contents of B.py to return some single value. But the contents of B.py may contain for example twenty variable assignments.
I guess then what I am really looking to do is not so much execute the contents of B.py within A.py, but moreover dynamically modify A.Py to contain, at some desired line in A.py, the contents of B.py. Then, obviously, execute the updated A.py.
Thoughts and tips much appreciated.
I don't think this is a good programming practice but you can use execfile to execute all the code in another file.
#a.py
a = a + 5
#b.py
a = 10
execfile("a.py")
print a
If you run b.py
it will print '15'.
做到这一点的方法是将你的代码放在一个函数里面,并从一个:
# b.py
def foo():
print 'b'
print 'c'
print 'd'
# a.py
import b
print 'a'
b.foo()
print 'm'
链接地址: http://www.djcxy.com/p/54798.html