How can I get my Python script to work using bash?
Question: I am new to this site so hopefully this is the correct location to place this
question.

I am trying to write a script using python for Linux, that:

  1. creates a file `file.txt`
  2. appends the output of the `'lsof'` command to `file.txt`
  3. read each line of the output and append them to an array.
  4. then print each line.

I'm basically just doing this to familiarize myself with using python for
bash, I'm new to this area so any help would be great. I'm not sure where to
go from here. Also if there is a better way to do this I'm open to that!

    
    
    #!/usr/bin/env python
    import subprocess
    
    touch = "touch file.txt"
    subprocess.call(touch, shell=True)
    xfile = "file.txt"
    
    connection_count = "lsof -i tcp | grep ESTABLISHED | wc -l"
    count = subprocess.call(connection_count, shell=True)
    
    if count > 0:
        connection_lines = "lsof -i tcp | grep ESTABLISHED >> file.txt"
    
    subprocess.call(connection_lines, shell=True)
    
    with open(subprocess.call(xfile, shell=True), "r") as ins:
        array = []
        for line in ins:
            array.append(line)
    
    for i in array:
        print i
    


Answer: `subprocess.call` returns the return code for the process that was started
(`$?` in bash). This is almost certainly not what you want -- and explains why
this line almost certainly fails:

    
    
    with open(subprocess.call(xfile, shell=True), "r") as ins:
    

(you can't open a number).

Likely, you want to be using `subprocess.Popen` with `stdout=subprocess.PIPE`.
Then you can read the output from the pipe. e.g. to get the count, you
probably want something like:

    
    
    connection_count = "lsof -i tcp | grep ESTABLISHED"
    proc = subprocess.POPEN(connection_count, shell=True, stdout=subprocess.PIPE)
    # line counting moved to python :-)
    count = sum(1 for unused_line in proc.stdout)
    

(you could also use `Popen.communicate` here)

Note, excessive use of `shell=True` is always a bit scary for me... It's much
better to chain your pipes together as demonstrated in the
[documentation](https://docs.python.org/2/library/subprocess.html#replacing-
shell-pipeline).

