Run shell command with input redirections from python 2.4?

SMTF picture SMTF · Sep 9, 2010 · Viewed 7.8k times · Source

What I'd like to achieve is the launch of the following shell command:

mysql -h hostAddress -u userName -p userPassword 
databaseName < fileName

From within a python 2.4 script with something not unlike:

cmd = ["mysql", "-h", ip, "-u", mysqlUser, dbName, "<", file]
subprocess.call(cmd)

This pukes due to the use of the redirect symbol (I believe) - mysql doesn't receive the input file.

I've also tried:

subprocess.call(cmd, stdin=subprocess.PIPE)

no go there ether

Can someone specify the syntax to make a shell call such that I can feed in a file redirection ?

Thanks in advance.

Answer

Constantin picture Constantin · Sep 9, 2010

You have to feed the file into mysql stdin by yourself. This should do it.

import subprocess
...
filename = ...
cmd = ["mysql", "-h", ip, "-u", mysqlUser, dbName]
f = open(filename)
subprocess.call(cmd, stdin=f)