简体   繁体   中英

how to insert code in a python script on-the-fly?

I'm not sure what this is called but this is what I need. A portion of code in a python script that is stored in another file. When the script runs, automatically the code is inserted.... something like a function but without arguments passing.

line 100
line 101
line 102
line 103
line 104

I want lines 101-103 to be stored in another file. When the python script executes, lines 101-103 are automatically inserted as it is. So now my code looks like this

line 100
read code from another file
line 104

Even better, if I am able to select which codes to insert in between lines 100 and 104 (eg from file 1 or file 2 depending on condition)
I don't want to use a function because it involves a lot of variable passing.

if condition==1:
    execfile('filename1.py',globals(),locals())
else:
    execfile('filename2.py',globals(),locals())

UPDATE: To show that variables are accessible back and forth:

f1.py:

x='ha'
execfile('f2.py',globals(),locals())
print('after: '+x)

f2.py

print('before: '+x)
x='blah'

Output:

before: ha
after: blah

Therefore, the value of x is passed to f2.py and the value set there is then accessible in f1.py.

You can use m4 for this. Put this in stuff.py :

print 1
print 2
include(other.py)
print 3
print 4

And this in other.py :

print 'a'
print 'b'

And run it this way:

m4 stuff.py | python

The above assumes a *nix system (because those have m4 ). If you have a system with a C compiler but no m4 , you can use the C preprocessor instead! Just change include(other.py) to #include "other.py" and run with cpp (or whatever the C preprocessor is called on your system) instead of m4 . This is rather more hacky, but perhaps more portable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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