[Tutor] Python popen command using cat > textfile .... how to terminate

Martin Walsh mwalsh at mwalsh.org
Fri May 15 01:31:32 CEST 2009

MK wrote:
> Hi there,
> i am using this code to send an "cat > ThisIsMyUrl" with popen.
> Of cos cat now waits for the CTRL+D command. 
> How can i send this command ?
> def console_command(cmd):
> 	print cmd
> 	console = os.popen(cmd,"r")
> 	output = console.read()
> 	console.close()
> 	return output
> command="cat > " + working_dir + "/" + subdir + "www.thisismyurl.com"
> console_command(command)

Ignoring the subprocess module for a moment, you could use os.popen2
instead of os.popen and then close the stdin fd to simulate a CTRL-D(EOF).

stdin, stdout = os.popen2(cmd)
stdin.write('This is line 1.\n')
stdin.close() # CTRL-D

With the subprocess module, you might do something like this (untested) ...

from subprocess import Popen, PIPE
console = Popen(
    cmd, shell=True, stdin=PIPE, stdout=PIPE, close_fds=True
console.stdin.write('This is line 1.\n')
# ... or just ...
# console.communicate('This is line 1.\n')

But, I can't figure out why you would want to do this. Or I should say
it's not at all clear to me what you are trying to accomplish --
although I suspect you are making it difficult for yourself.

Can you provide a brief explanation of what you are trying to achieve?


More information about the Tutor mailing list