简体   繁体   English

如何在Python脚本中即时插入代码?

[英]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. python脚本中存储在另一个文件中的一部分代码。 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. 我希望将101-103行存储在另一个文件中。 When the python script executes, lines 101-103 are automatically inserted as it is. 执行python脚本时,系统会按原样自动插入第101-103行。 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) 更好的是,如果我能够选择要在第100和104行之间插入的代码(例如,根据条件从文件1或文件2中插入)
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: f1.py:

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

f2.py 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. 因此,x的值将传递到f2.py,然后可以在f1.py中访问在那里设置的值。

You can use m4 for this. 您可以为此使用m4 Put this in stuff.py : 把它放在stuff.py

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

And this in other.py : 而这在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 ). 上面假设一个* nix系统(因为那些具有m4 )。 If you have a system with a C compiler but no m4 , you can use the C preprocessor instead! 如果您的系统具有C编译器但没有m4 ,则可以使用C预处理器! 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 . 只需将include(other.py)更改为#include "other.py"并使用cpp (或系统上调用的C预处理程序)而不是m4 This is rather more hacky, but perhaps more portable. 这比较hacky,但可能更便于携带。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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