Ivan
Ivan

Reputation: 409

Python not printing newline

I have script that seems to have stopped working after my latest upgrade. To find the problem, I wrote a little script:

import subprocess

hdparm = subprocess.Popen(["xargs","echo"],
                stdin=subprocess.PIPE)

hdparm.stdin.write("Hello\n")
hdparm.stdin.write("\n")
hdparm.stdin.close()
hdparm.wait()
quit()

This just prints "Hello" and a new line, but I expect two newlines. What's causing this? (I am using 2.7.3 at the moment)

EDIT: Here is the problematic script (edited for clarity):

hdparm = subprocess.Popen(["hdparm", "--please-destroy-my-drive", "--trim-sector-ranges-stdin", "/dev/sda"],
               stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
hdparm_counter = 0
for rng in ranges_to_trim:
    hdparm.stdin.write("%d:%d\n" % (rng["begin"],rng["length"]))
    hdparm_counter += 1
    if hdparm_counter > 63:
         hdparm.stdin.write("\n")
         hdparm_counter = 0
if hdparm_counter != 0:
    hdparm.stdin.write("\n")
hdparm.stdin.close()
hdparm.wait()

EDIT: I believe the problem is with my script itself. I need to send EOF to hdparm to make it do whatever it is supposed to.

Upvotes: 0

Views: 259

Answers (1)

FatalError
FatalError

Reputation: 54621

From the xargs man page:

This manual page documents the GNU version of xargs. xargs reads items from the standard input, delimited by blanks (which can be protected with double or single quotes or a backslash) or newlines, and executes the command (default is /bin/echo) one or more times with any initial-arguments followed by items read from stan‐ dard input. Blank lines on the standard input are ignored.

(emphasis added).

Also, to add -- the newline you see is from echo itself. xargs doesn't pass it along anyway.

Upvotes: 5

Related Questions