user13977273
user13977273

Reputation:

Python subprocess.check_output() for general shell command

I am working on a simple Tkinter GUI for SQL tables. Obviously, I have had to use shell commands, and I have been struggling with the subprocess shell system.

For example, subprocess.check_output('ls') will run ls, but to run ls -l, you need to use subprocess.check_output(['ls', '-l']). I have not found a way to get the output of a more complex command, e.g. cat test.sql | sqlite3 test.db (run sqlite3 on test.db, then list out test.sql at the prompt).

Things I've tried

I ended up just using the os.system() and os.popen() commands, but people say that using these is not recommended. What should I do?

Upvotes: 1

Views: 6439

Answers (1)

Max Feinberg
Max Feinberg

Reputation: 840

Looking at the subprocess.check_output documentation here, you have 2 options:

output = subprocess.check_output("cat test.sql | sqlite3 test.db", shell=True)

or

from subprocess import Popen, PIPE

p1 = Popen(["cat", "test.sql"], stdout=PIPE)
p2 = Popen(["sqlite3", "test.db"], stdin=p1.stdout, stdout=PIPE)
p1.stdout.close()  # Allow p1 to receive a SIGPIPE if p2 exits.
output = p2.communicate()[0]

Upvotes: 1

Related Questions