-1

I am having problem with logic and syntax in Python for opening program and executing program.

For an example, I have figured out how to open a program with python code by doing so:

import os 
os.system("start c:/test/sqlite3 test.db3)

With this example code I am opening an sqlite3 (I know there is an sqlite3 library in Python - I am trying to understand OS right now.)

How could execute following command with this open file?

.read test.sql

I would appreciate if you would explain a logic to me in brief. Thank you.

filtertips
  • 801
  • 3
  • 12
  • 25
  • If you are trying to understand OS then stick to OS related commands. You will get much better use out of the sqlite library when doing work with your sqlite databases. You'll just confuse yourself and pick up bad practices if you mix and match libraries – Alan Kavanagh Jun 04 '16 at 13:12
  • No, like i said, this is just a test. I don't intend to use mixed libraries, i am trying to figure out how to manipulate with OS. – filtertips Jun 04 '16 at 13:14
  • os.system() is basically the same as opening up a command prompt and typing commands in. You could chain multiple OS.system() calls to write a script, but this is just bad practice and complete misuse of the libraries.. os.system('cd ../'), os.system('dir'), os.system('cd ../'), os.system('dir') for example will run them 4 commands one after the other.. – Alan Kavanagh Jun 04 '16 at 13:17
  • Likewise, if you open up a command prompt and type in 5 commands to execute some database related work, if you copy all them inside a os.system(), it should do the exact same thing – Alan Kavanagh Jun 04 '16 at 13:18
  • Take a look at the subprocess module https://docs.python.org/3/library/subprocess.html .. this supersedes the os library. Some examples: http://www.cyberciti.biz/faq/python-run-external-command-and-get-output/ – Levon Jun 04 '16 at 13:36

1 Answers1

2

First, os.system is no longer recommended. Use the subprocess module instead.

To open a programm with subprocess use:

import subprocess

p = subprocess.Popen(['command', 'arguments'])

With Popen you can also use PIPE to communicate with the process via stdin. E.g.:

p = subprocess.Popen(['command', 'args'], stdin=subprocess.PIPE)

result = p.communicate(b"Any input that goes to stdin")

# do whatever you want to do with the result

Documentation about Popen, subprocess module and communicate.

Erich
  • 1,838
  • 16
  • 20