Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run shell command with input redirections from python 2.4?

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.

like image 785
SMTF Avatar asked Sep 09 '10 19:09

SMTF


People also ask

Can you run shell commands from Python?

Python allows you to execute shell commands, which you can use to start other programs or better manage shell scripts that you use for automation. Depending on our use case, we can use os. system() , subprocess. run() or subprocess.

How do I run a shell in Python?

To run the Python Shell, open the command prompt or power shell on Windows and terminal window on mac, write python and press enter. A Python Prompt comprising of three greater-than symbols >>> appears, as shown below. Now, you can enter a single statement and get the result.

How do I run an echo command in Python?

subprocess.Popen() Here. we are using the subprocess. Popen() method to execute the echo shell script using Python. You can give more arguments to the Popen function Object() , like shell=True, which will make the command run in a separate shell.


1 Answers

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)
like image 151
Constantin Avatar answered Oct 16 '22 10:10

Constantin