簡體   English   中英

Python:如何在Tex中輸入\\ input這樣的python代碼部分?

[英]Python: how to input python-code part like \input in Tex?

我想在Python中\\input{Sources/file.tex} 如何在Python中完成?

[添加]

假設我要將數據輸入到: print("My data is here"+<input data here>)

數據

1, 3, 5, 5, 6

內置的execfile函數可以執行您要求的操作,例如:

filename = "Sources/file.py"
execfile( filename )

這將執行Sources/file.py的代碼,就像該代碼已嵌入到當前文件中一樣,因此與C中的#include或LaTeX中的\\input非常相似。

請注意, execfile還允許使用兩個可選參數,允許您指定應相對於代碼執行的全局變量和局部變量,但是在大多數情況下,這不是必需的。 有關詳細信息,請參見pydoc execfile

偶爾有正當理由要使用execfile 但是,出於構造大型Python程序的目的,通常將代碼分成放置在PYTHONPATH中某個位置的模塊,並使用import語句加載它們,而不是使用execfile執行它們。 execfile相比, import的優點包括:

  • 導入的函數將使用模塊的名稱進行限定,例如module.myfunction而不是myfunction
  • 您的代碼無需對文件在文件系統中的位置進行硬編碼。

您無法在Python中做到這一點。 您可以從其他模塊import對象。

otherfile.py:

def print_hello():
    print "Hello World!"

main.py

import otherfile
otherfile.print_hello() # prints Hello World!

參見python教程

假設您在“ my_file.py”中有代碼。 不在方法中的任何行將在執行時被執行:

import my_file

因此,例如,如果my_file.py中包含以下代碼:

print "hello"

然后在解釋器中鍵入:

import my_file

您將看到“你好”。

我的問題顯然太廣泛了,因為各種各樣的答復都暗示-沒有一個人完全反對這個問題。 jchl針對您要執行python代碼的場景。 THC4k解決了您要使用模塊中外部對象的情況。 正如Xavier Ho提到的那樣,muckabout的答復是不當行為,為什么它在地面上也可以同時使用exec時使用import ,這是對狗的特權最小的原則。 仍然缺少一件事,可能是因為標題中的術語python-code與添加包含整數的data之間存在沖突-很難斷言數據是python-code但是代碼說明了如何input數據, evaluationsexecutable代碼。

#!/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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM