when is 'commands' preferable to 'popen' subprocess?

I'm apprenticing into system administration without schooling, so sometimes I'm missing what is elementary information to many others.

I'm attempting to give my stdout line another argument before printing, but I'm not sure which process I should use, and I'm a bit fuzzy on the commands for subprocess if that's what I should be using.

My current code is:

f = open('filelist', 'r')
searchterm = f.readline()
f.close()|
#takes line from a separate file and gives it definition so that it may be callable.

import commands
commands.getoutput('print man searchterm')

This is running, but not giving me an ouput to the shell. My more important question is though, am I using the right command to get my preferred process? Should I be using one of the subprocess commands instead? I tried playing around with popen, but I don't understand it fully enough to use it correctly.

Ie, I was running

subprocess.Popen('print man searchterm') 

but I know without a doubt that's not how you're supposed to run it. Popen requires more arguments than I have given it, like file location and where to run it (Stdout or stderr). But I was having trouble making these commands work. Would it be something like:

subprocess.Popen(pipe=stdout 'man' 'searchterm')
#am unsure how to give the program my arguments here.  

I've been researching everywhere, but it is such a widely used process I seem to be suffering from a surplus of information rather than not enough. Any help would be appreciated, I'm quite new.

Preemptive thanks for any help.


The cannonical way to get data from a separate process is to use subprocess (commands is deprecated)

import subprocess
p = subprocess.Popen(['print','man','searchitem'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdoutdata, stderrdata = p.communicate()

Note that some convenience functions exist for splitting strings into lists of arguments. Most notably is shlex.split which will take a string and split it into a list the same way a shell does. (If nothing is quoted in the string, str.split() works just as well).


commands在Python 2.6和更高版本中已被弃用,并且已在Python 3中被删除。即使您使用Python 2.5或更早版本,也可能没有在新代码中更好的情况。


From the docs:

Deprecated since version 2.6: The commands module has been removed in Python 3. Use the subprocess module instead.

To run man searchterm in a separate process and display the result in the terminal, you could do this:

import subprocess
proc = subprocess.Popen('man searchterm'.split())
proc.communicate()
链接地址: http://www.djcxy.com/p/13480.html

上一篇: 子过程输出到PIPE并直接输出到stdout

下一篇: 什么时候'命令'更喜欢'popen'子流程?