tags:

views:

74

answers:

3

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
+2  A: 

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

THC4k
Extending THC4k's answer, Python's import isn't just a copy-and-paste pre-processor like C #include. Instead Python will actually process the names of the classes and functions and remember them in a look-up dict so you can use them.
Xavier Ho
A: 

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".

muckabout
This is bad practice, though.
Xavier Ho
In most contexts, yes. But latex isn't exactly an advanced programming language :)
muckabout
+4  A: 

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:

  • Imported functions get qualified with the name of the module, e.g. module.myfunction instead of just myfunction.
  • Your code doesn't need to hard-code where in the filesystem the file is located.
jchl