python - Import vs open for input file -


i have input file variables use in python program. better bring in variables using import:

import imp inputdata = imp.load_source(...) 

or better read file using:

for line in open('inputfile'): 

are there advantages or disadvantages either way?

thanks in advance!

there advantages , disadvantages each. line-by-line approach absolutely "safer", since you're not executing whatever arbitrary code find in source file. however, since don't seem concerned malicious users, i'll assume that's not issue in environment. obvious disadvantage line-by-line approach it's more work while writing it. imp.load_source far easier code.

i believe "correct" way use built-in function execfile, since case exact reason function exist. way, can give whole execution own namespace. it's similar in function imp.load_source, except doesn't create module. you'd this:

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

it's worth noting 1 more time if can't trust users, should not allow execution of arbitrary code! if it's pain, may better line-by-line parsing or use other format input/config file if can't trust file not contain malicious code.


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -