19

Code:

import subprocess

def printit():
    for i in range(6):
        for j in range(6):
            query = "select rxpkts, txpkts from ./log.csv where datapath = "+str(i)+" and port = "+str(j)
            fileName = str(i)+"_"+str(j)+".csv"
            with open(fileName, "w+"):
                p = subprocess.Popen(["python", "q", "-H", "-d", ",", query], stdout=fileName)

printit()

Error:

$ python processLog.py 
Traceback (most recent call last):
  File "processLog.py", line 11, in <module>
    printit()
  File "processLog.py", line 9, in printit
    p = subprocess.Popen(["python", "q", "-H", "-d", ",", query], stdout=fileName)
  File "/usr/lib/python2.7/subprocess.py", line 702, in __init__
    errread, errwrite), to_close = self._get_handles(stdin, stdout, stderr)
  File "/usr/lib/python2.7/subprocess.py", line 1128, in _get_handles
    c2pwrite = stdout.fileno()
AttributeError: 'str' object has no attribute 'fileno'

What could be the issue? I am using q

sinhayash
  • 2,693
  • 4
  • 19
  • 51
  • Note that StringIO, while of the proper subclass, will not work. See http://stackoverflow.com/questions/5903501/attributeerror-stringio-instance-has-no-attribute-fileno for more information. – Charles Merriam Mar 05 '17 at 17:33

1 Answers1

38

The stdout argument needs a file object, not the string for the filename.

Try using -

import subprocess

def printit():
    for i in range(6):
        for j in range(6):
            query = "select rxpkts, txpkts from ./log.csv where datapath = "+str(i)+" and port = "+str(j)
            fileName = str(i)+"_"+str(j)+".csv"
            with open(fileName, "w+") as f:
                p = subprocess.Popen(["python", "q", "-H", "-d", ",", query], stdout=f)

printit()
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
  • thanks a lot. Surprisingly how many examples on internet just used the filename instead of file object. – oldpride Jul 04 '23 at 03:30