将子进程的输出重定向到文件

时间:2015-02-04 20:28:18

标签: python popen io-redirection

我正在尝试使用Python将Nmap扫描的输出重定向到文本文件。

这是我的代码:

outputName = raw_input("What is the output file name?")
fname = outputName
with open(fname, 'w') as fout:
     fout.write('')

command = raw_input("Please enter an Nmap command with an IP address.")
args = shlex.split(command)
proc = subprocess.Popen(args,stdout=fname)

错误:

Traceback (most recent call last):
  File "mod2hw4.py", line 17, in <module>
    proc = subprocess.Popen(args,stdout=fname)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 701, in __init__
    errread, errwrite), to_close = self._get_handles(stdin, stdout, stderr)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1127, in _get_handles
    c2pwrite = stdout.fileno()
AttributeError: 'str' object has no attribute 'fileno'

2 个答案:

答案 0 :(得分:2)

正如上面提到的那样,你必须传递一个打开的文件;该文件的名称将无效。您应该使用您创建的相同上下文(with块)执行此操作;尝试重新安排它:

outputName = raw_input("What is the output file name?")
fname = outputName

command = raw_input("Please enter an Nmap command with an IP address.")
args = shlex.split(command)

with open(fname, 'w') as fout:
    proc = subprocess.Popen(args,stdout=fout)
    return_code = proc.wait()

现在不是subprocess.Popen而是stdout=fout,而不是stdout=fname。由with语句创建的上下文管理器可确保在nmap进程完成时关闭文件,即使发生异常也是如此。

答案 1 :(得分:1)

来自文档:

  

stdin,stdout和stderr分别指定执行程序的标准输入,标准输出和标准错误文件句柄。有效值为PIPE,现有文件描述符(正整数),现有文件对象和无。

因此文件名不是stdout参数的有效值。

我想你想要这个:

proc = subprocess.Popen(args,stdout=open(fname, 'w'))

或者更好的是,只需将所有内容保留在with块中:

with open(fname, 'w') as fout:
    fout.write('')

    command = raw_input("Please enter an Nmap command with an IP address.")
    args = shlex.split(command)
    proc = subprocess.Popen(args,stdout=fout)