1

I am calling a second python script that is written for the command line from within my script using

os.system('insert command line arguments here')

this works fine and runs the second script in the terminal. I would like this not to be output in the terminal and simply have access to the lists and variables that are being printed. Is this possible using os.system? Or, do I need to use something else?

miltonjbradley
  • 601
  • 2
  • 10
  • 21
  • it is best to import the module instead of running it as a script. See [Call python script with input with in a python script using subprocess](http://stackoverflow.com/q/30076185/4279) – jfs Jun 17 '16 at 03:15

2 Answers2

1

You can use the subprocess module and redirect its output through a pipe.

For example, to get the list of file in current directory.

import subprocess
proc = subprocess.Popen(['ls'], stdout=subprocess.PIPE)
print(proc.stdout.readlines())

More details here Redirecting stdio from a command in os.system() in Python

Edit: if you are trying to pass arguments to subprocess.Popen each one gets its own set of quotes.

proc = subprocess.Popen(['python','test.py','-b','-n'], stdout=subprocess.PIPE)

And the doc https://docs.python.org/2/library/subprocess.html

Community
  • 1
  • 1
SnoozeTime
  • 363
  • 1
  • 9
  • Thank-you for the answer. This works for 'ls' but when I try to run the python script i get this error: OSError: [Errno 2] No such file or directory. But my script is in the same directory as the second script I am trying to run. Any ideas? – miltonjbradley Jun 17 '16 at 02:08
  • I tried with two scripts in the same directory. Using proc = subprocess.Popen(['python','script.py'], stdout=subprocess.PIPE) it worked perfectly. Make sure you are executing the python script in the correct directory – SnoozeTime Jun 17 '16 at 02:11
  • I wasn't splitting up the commands, I was writing 'python','script.py' as 'python script.py'. This fix the directory problem, bit now it is simply printing an empty list. I can confirm that the script works when I simply print it to the console. – miltonjbradley Jun 17 '16 at 02:19
  • Inside my test script, I just wrote print("something"). You can check it is working on your computer and adapt your script accordingly – SnoozeTime Jun 17 '16 at 02:25
  • I got it to work. I was trying to pass arguments without another set of quotes. Thanks for the help! – miltonjbradley Jun 17 '16 at 02:27
  • No problem, don't forget to mark the question answered if it is ok =) – SnoozeTime Jun 17 '16 at 02:28
1

Alternatively to snoozeTime's answer you could use:

import subprocess
output = subprocess.check_output(['ls'])
print(output)
hussamh10
  • 129
  • 9