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

Redirect output of subprocess to file

我正在尝试使用 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'

来自文档:

stdin, stdout and stderr specify the executed program’s standard input, standard output and standard error file handles, respectively. Valid values are PIPE, an existing file descriptor (a positive integer), an existing file object, and None.

所以文件名不是 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)

正如Paulo在上面提到的,你必须传递一个打开的文件;文件名将不起作用。您可能应该使用您创建的相同上下文(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=fnamewith 语句创建的上下文管理器可确保在 nmap 进程完成时关闭文件,即使发生异常也是如此。