piyush-balwani
piyush-balwani

Reputation: 544

tail command not giving correct answer for subprocess.Popen

When running below command through terminal, it is giving correct output, i.e. excluding top head 6 lines, displaying remaining lines of data.out .

tail -n +6 data.out

But when same command is processing through subprocess.Popen as given in below code:

fin = open('data.out')
fout = file('data1.out','w')
line = 6
lineno = "-n +" + str(line)
p2 = subprocess.Popen(["tail",lineno], stdin=fin, stdout=fout)
errcode = p2.wait()
fin.close()
fout.close()

This is storing last 6 lines of data.out in data1.out file, which is incorrect. This is storing output of tail -n 6 data.out, not of given and expected tail -n +6 data.out

Upvotes: 2

Views: 1262

Answers (1)

Jean-François Fabre
Jean-François Fabre

Reputation: 140276

don't mix multi-arguments with list arguments

lineno = "-n +" + str(line)  # wrong: 2 arguments seen as one
p2 = subprocess.Popen(["tail",lineno], stdin=fin, stdout=fout)

you have 2 arguments here, and the +line part is probably ignored by tail. Instead, just pass one argument per list item:

p2 = subprocess.Popen(["tail","-n","+"+str(line)], stdin=fin, stdout=fout)

maybe clearer using format:

p2 = subprocess.Popen(["tail","-n","+{}".format(line)], stdin=fin, stdout=fout)

Upvotes: 2

Related Questions