user8675309
user8675309

Reputation: 181

Import vs open for input file

I have an input file with variables that I would like to use in a python program. Is it better to bring in the variables using import:

import imp
inputData = imp.load_source(...)

Or is it better to read the file using:

for line in open('inputfile'):

Are there advantages or disadvantages either way?

Thanks in advance!

Upvotes: 0

Views: 1820

Answers (3)

unutbu
unutbu

Reputation: 880399

If you want Python to execute the statements in the file, it is better to import than to read the file in as a string (which is what open(...) would lead to).

And if you are going to be importing the file, you might as well put it in a directory listed in your PYTHONPATH and simply use

import config

On the other hand, if you do not control the contents of the file and the contents are supplied by potentially malicious users, then it is imperative that you parse the contents first without blindly executing it contents.

This is no a choice to be weighed with pros and cons. If you care about security then you must not import the file.

Upvotes: 0

Henry Keiter
Henry Keiter

Reputation: 17188

There are certainly advantages and disadvantages to each. The line-by-line approach is absolutely "safer", since you're not simply executing whatever arbitrary code you find in the source file. However, since you don't seem to be concerned so much about malicious users, I'll assume that's not an issue in your environment. The obvious disadvantage to the line-by-line approach is that it's more work for you while writing it. imp.load_source is clearly far easier to code.

I believe the "correct" way to do this is to use the built-in function execfile, since this case is basically the exact reason for this function to exist. This way, you can give the whole execution its own namespace. It's similar in function to imp.load_source, except that it doesn't create a module. You'd do something like this:

loaded_variables = {}
execfile('foo.bar', loaded_variables)

It's worth noting one more time that if you can't trust your users, you should not allow execution of arbitrary code! Even if it's a pain, it may be better to do a line-by-line parsing or use some other format for your input/config file if you can't trust that the file will not contain malicious code.

Upvotes: 2

Bakuriu
Bakuriu

Reputation: 101999

When you import a file the code is executed. You should never allow execution of arbitrary code. Think carefully before opening such a huge breach in the security.

There are a lot of file-formats which can be parsed easily and that you can use instead, or you can even create your own format. Especially if the assignments contains only literals, and not arbitrary expressions.

Upvotes: 0

Related Questions