I want to input code in Python like \input{Sources/file.tex}
. How can I do it in Python?
[added]
Suppose I want to input data to: print("My data is here"+<input data here>)
.
Data
1, 3, 5, 5, 6
I want to input code in Python like \input{Sources/file.tex}
. How can I do it in Python?
[added]
Suppose I want to input data to: print("My data is here"+<input data here>)
.
Data
1, 3, 5, 5, 6
You can't do that in Python. You can import
objects from other modules.
otherfile.py:
def print_hello():
print "Hello World!"
main.py
import otherfile
otherfile.print_hello() # prints Hello World!
See the python tutorial
Say you have code in "my_file.py". Any line which is not in a method WILL get executed when you do:
import my_file
So for example if my_file.py has the following code in it:
print "hello"
Then in the interpreter you type:
import my_file
You will see "hello".
The built-in execfile
function does what you ask, for example:
filename = "Sources/file.py"
execfile( filename )
This will execute the code from Sources/file.py
almost as if that code were embedded in the current file, and is thus very similar to #include
in C or \input
in LaTeX.
Note that execfile
also permits two optional arguments allowing you to specify the globals and locals dicts that the code should be executed with respect to, but in most cases this is not necessary. See pydoc execfile
for details.
There are occasional legitimate reasons to want to use execfile
. However, for the purpose of structuring large Python programs, it is conventional to separate your code into modules placed somewhere in the PYTHONPATH and to load them using the import
statement rather than executing them with execfile
. The advantages of import
over execfile
include:
module.myfunction
instead of just myfunction
.