Difference between Popen and open() for reading a file
davea at ieee.org
Thu Apr 22 15:18:15 EDT 2010
> I was reading something from a code review a little while ago and saw
> something that's got my curiosity up...
> Say I had a file, foo.txt that I wanted to read from, only one time
> and only read.
> So what's the difference between this:
> mylist = Popen(["cat","foo.txt"], stdout=PIPE).communicate().splitlines()
> and this:
> f = open('foo.txt')
> mylist = f.readlines()
> Is there a reason why you would not use subprocess.Popen for this,
> other than just not relying on external programs to perfrom the task?
> what if that file only has one line in it, and that's all you're
> interested in, and the file is guaranteed to only have that one line
> it it?
> For example:
> say foo.txt contained only the number 123456789
> what's wrong with doing this:
> my_int = int(commands.getoutput('cat foo.txt')
> or via the subprocess.Popen method mentioned above?
The same difference as between handing the paper boy three bucks, versus
flying to London to open an account, making a deposit, going to a branch
in Sydney and asking for a bank check, then flying back home and taking
the paper boy with you to the bank to cash it.
When you use subprocess, you're creating a whole new process in order
the copy the file into another one, which you then read. Takes much
more resources, time, and is much more likely to break. For example,
what if this program runs on a system without "cat" ?
More information about the Python-list