by btilly · 15y ago · 0 comments
`your system call and args`
subprocess.Popen(['your', 'system', 'call', 'and', 'args'], stdout=subprocess.PIPE).communicate()[0]
The former is the traditional syntax supported in various shells, Perl, and Ruby. The latter is what you need if you want your code to run in Python 2.6.And this is before we get into the fact that the minutia of syntax and layout is only a minor factor in the maintainability of large projects.
Sorry, but you're wrong. The os.system call is the equivalent of Perl's system call. It runs an external command and gives you a return code, but does not give you the text generated by said system call. The officially recommended (as of Python 2.6) way to get said text is what I wrote.
The deprecated but possibly still working solution is to use os.popen. That is cleaner for this common use case, but I chose to stick to the the officially recommended solution instead.
Eventually the Python folks realized that the blessed One True Way to do it was actually pretty horrible, and so they added subprocess.check_output in 2.7.
subprocess.check_output("ls -al", shell=True)
Note the possible resulting security vulnerabilities.
os.popen() is still available in python3, and uses subprocess.Popen() internally.
import commands print commands.getoutput("your system call and args")
Perl desperately needs a built-in backtick() function:
my $x = backtick(qw(my-program -l -V), "--option=$something", @files);
Maybe in perl you'd call it ``() or something instead of backtick().Of course the first syntax breaks when one of the arguments has a space or any other meta-character in it.
To be absolutely clear, I actually like Python. I just strongly disagree with the belief that Python magically ensures readability. Particularly because my impression is that people who think that Python magic pixie dust automatically makes for good code are actually more likely to write bad code. (Because they have not thought deeply enough about what makes code good.)
Therefore I can't agree that the Python that I presented is as good as is possible for a general purpose programming language.