如何让Popen写入文件

时间:2017-09-29 13:54:54

标签: python popen fwrite python-2.6

所以我已经制作了IP / Hostname扫描程序,我试图在输出ping或无法运行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()

1 个答案:

答案 0 :(得分:2)

如果我正确理解您的问题,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中的错误