Pyderman
Pyderman

Reputation: 16229

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?

e.g. 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.

Upvotes: 0

Views: 2682

Answers (2)

Faruk Sahin
Faruk Sahin

Reputation: 8726

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'.

Upvotes: 1

solarc
solarc

Reputation: 5738

The way to do this would be placing your code in b inside a function and import it from a:

# b.py
def foo():
    print 'b'
    print 'c'
    print 'd'


# a.py
import b

print 'a'
b.foo()
print 'm'

Upvotes: 0

Related Questions