Python:如何像在Tex中使用\input一样输入Python代码部分?
我想在Python中输入代码,比如 \input{Sources/file.tex}
。我该怎么做呢?
[补充说明]
假设我想把数据输入到这个地方: print("我的数据在这里" + <输入数据在这里>)
。
数据
1, 3, 5, 5, 6
4 个回答
在Python中,你不能这样做。你可以从其他模块中导入
对象。
otherfile.py:
def print_hello():
print "Hello World!"
main.py
import otherfile
otherfile.print_hello() # prints Hello World!
可以查看这个Python教程了解更多信息。
内置的 execfile
函数可以按照你的要求执行代码,比如:
filename = "Sources/file.py"
execfile( filename )
这段代码会执行 Sources/file.py
文件中的代码,就好像这些代码直接写在当前文件里一样。这和 C 语言中的 #include
或 LaTeX 中的 \input
很相似。
需要注意的是,execfile
还允许你传入两个可选参数,这样你可以指定代码执行时使用的全局变量和局部变量字典,但在大多数情况下,这并不是必要的。想了解更多细节,可以查看 pydoc execfile
。
有时确实有合理的理由想要使用 execfile
。不过,在构建大型 Python 程序时,通常的做法是将代码分成模块,并把它们放在 PYTHONPATH 中,然后用 import
语句来加载这些模块,而不是用 execfile
来执行它们。使用 import
相比于 execfile
有以下几个好处:
- 导入的函数会带上模块的名字,比如
module.myfunction
,而不仅仅是myfunction
。 - 你的代码不需要硬编码文件在文件系统中的位置。
我的问题显然太宽泛了,回复的多样性就说明了这一点——没有一个回答真正解决了问题。jchl的回答针对的是你想执行Python代码的情况。THC4k则是讨论你想使用外部模块中的对象的情况。muckabout的回复是不好的做法,正如Xavier Ho提到的,为什么要用import
,而可以用exec
呢?这完全违背了最小权限原则。还有一个问题没有解决,可能是因为标题中的python-code
和后面提到的包含整数的data
之间的冲突——很难说数据就是python-code
,但代码解释了如何输入
数据、评估
和可执行
代码。
#!/usr/bin/python
#
# Description: it works like the input -thing in Tex,
# you can fetch outside executable code, data or anything you like.
# Sorry I don't know precisely how input(things) works, maybe misusing terms
# or exaggerating.
#
# The reason why I wanted input -style thing is because I wanted to use more
# Python to write my lab-reports. Now, I don't need to mess data with
# executions and evalutions and data can be in clean files.
#TRIAL 1: Execution and Evaluation not from a file
executeMe="print('hello'); a = 'If you see me, it works'";
exec( executeMe )
print(a);
#TRIAL 2: printing file content
#
# and now with files
#
# $ cat IwillPrint007fromFile
# 007
f = open('./IwillPrint007fromFile', 'r');
msg = f.read()
print("If 007 == " + msg + " it works!");
# TRIAL 3: Evaluation from a file
#
# $cat IwillEvaluateSthing.py
# #!/usr/bin/python
# #
# # Description:
#
#
# evaluateMe = "If you see me again, you are breaking the rules of Sky."
f = open('./IwillEvaluateSthing.py', 'r');
exec(f.read());
print(evaluateMe);