Home > OS >  file read/write Popen python
file read/write Popen python

Time:05-27

I'm trying to Read/Write process file with command grep and cut to get part of the IP address using pipe operator, here is the process simply written.

import subprocess as sub
import shlex

    def discover_Host():    
     with open("Get_IP.txt", "w ") as q_process:
       cmd1 = "grep Host xmap_ip.gnmap"
       cmd2 = "cut -d ' ' -f 2"
       arg1 = shlex.split(cmd1)
       arg2 = shlex.split(cmd2)
    
       proc1 = sub.Popen(args1, stdout = sub.PIPE)
       proc2 = sub.Popen(args2, stdin = proc1.stdout, stdout = q_process)
    
       proc1.stdout.close()
       out, err = proc2.communicate()
    return

Now the file Get_IP.txt contains data like this Host: 172:22:179:156 (abc.efg.net) Status: Up so I'm trying to get only IP address from it as I run the grep and cut command with pipe directly on the terminal it works but as I try it with SubProcess it doesn't write on the file.

CodePudding user response:

There's no reason to use shell commands for this, it can be done entirely in Python.

def discover_Host():
    with open('xmap_ip.gnmap') as xmap, open("Get_IP.txt", "w") as outfile:
        for line in xmap:
            if 'Host' in line:
                field2 = line.split(' ')[1]
                print(field2, file=outfile)

CodePudding user response:

You can combine both commands in one call, but you must pass shell to sub.Popen:

   cmd1 = "grep Host xmap_ip.gnmap | cut -d ' ' -f 2"
   proc1 = sub.Popen(cmd1, shell=True)
  • Related