如何让 Popen 写入文件

How to get Popen to write to a file

所以我制作了 IP/Hostname 扫描仪,我试图在它 运行 ping 或未能 运行 之后将输出打印到文件平。我的问题是出现了这些错误:

Traceback (most recent call last):
  File ".\IPlookup.py", line 59, in <module>
    print >> IPtext," is down!", 'Filename:', filename
AttributeError: 'str' object has no attribute 'write'

Traceback (most recent call last):
 File ".\IPlookup.py", line 55, in <module>
   print >> output, 'Filename:', filename
AttributeError: 'Popen' object has no attribute 'write'

这就是实际代码的样子

#This here code is used to scan IP's hostnames or files and ping them, then if there is 0% packet loss it does an nslookup...

import sys
import os
import subprocess

#This is supposed to print the output to a txt file but boy howdy does it not work

elif userType == '-l':
    IPtext = raw_input("Please enter IP or URL: ")
    response = os.system("ping -c 1 " + IPtext)
    output = subprocess.Popen(['nslookup',IPtext])
    if response == 0:
        f = open('out.txt','w')
        print >> output, 'Filename:', filename
        f.close()
    else:
        f = open('out.txt','w')
        print >> IPtext," is down!", 'Filename:', filename
        f.close()

有没有办法让 str 输出和 popen 都写入文件,或者我是否需要完全更改我的代码?

通过这样做解决了我的部分问题

elif userType == '-l':
    with open('out.txt','a') as f:
        IPtext = raw_input("Please enter IP or URL: ")
        response = os.system("ping -c 1 " + IPtext)
        output = subprocess.Popen(['nslookup',IPtext])
        if response == 0:
            f.write(output)
            f.close()
        else:
            f.write(IPtext)
            f.close()

现在唯一不起作用的是打印出抛出错误的 popen

TypeError: 参数 1 必须是字符串或只读字符缓冲区,而不是 Popen

    elif userType == 't -l' or userType == 't --logfile':
       with open('Pass.txt','a') as f:
       IPtext = raw_input("Please enter IP or URL: ")
       response = os.system("ping -c 1 " + IPtext)
       merp = subprocess.Popen(['nslookup',IPtext], stdout=subprocess.PIPE)
       out, err = merp.communicate()
       if response == 0:
           f.write('\n')
           f.write(out)
           f.close()
       else:
           with open('Fail.txt','a') as f:
               f.write('\n')
               f.write(IPtext)
               f.close()

如果我正确理解你的问题,f.write(output) 行会抛出 TypeError。

之所以如此,是因为在您的情况下输出是一个 Popen 对象。 替换这些行:

output = subprocess.Popen(['nslookup',IPtext])
    if response == 0:
        f.write(output)

这些:

# ... everything before your .subprocess.Popen(...) line
popen = subprocess.Popen(['nslookup',IPtext], stdout=subprocess.PIPE)# this is executed asynchronus
popen.wait() # this is to wait for the asynchron execution
resultOfSubProcess, errorsOfSubProcess = popen.communicate()
# resultOfSubProcess should contain the results of Popen if no errors occured
# errorsOfSubProcess should contain errors, if some occured
    if response == 0:
        f.write(resultOfSubProcess)
        # ... the rest of your code

编辑:您可能还想在继续之前检查空的 resultOfSubProcess 变量或 errorsOfSubProcess 中的错误