2
$\begingroup$

I do this in the Python Console in Blender 2.64 on Ubuntu 11.04:

>>> import os
>>> os.system('ls')
0

>>> os.system('ls /')
0

>>> os.system('echo aa')
0

If that 0 is return status, it implies the command should have executed successfully - yet nothing is printed to the terminal? However, if I do:

>>> os.system('echo aa > /tmp/test.txt')
0

... then there is a /tmp/test.txt file created, with the expected contents ?!

So, the problem is apparently getting the stdout of the system shell routed to the Python console. Is there any way to get this done, so I can see the output of, say, ls or echo in the Python console?

$\endgroup$

1 Answer 1

2
$\begingroup$

Ok, it seems subprocess can be used instead; note here you have to specify the shell explicitly, e.g. try pasting this script in Python Console:

import subprocess
p = subprocess.Popen(['bash', '-c', 'echo AAaa'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
print(out, err)

The output to that is:

>>> ...
>>> print(out, err)
b'AAaa\n' b''

Note that if you intend to do "piping" bash commands, things get a tad bit more complicated (see Python - How to call bash commands with pipe? - Stack Overflow); so for instance, to call echo BBbb | xsel -b and actually have it succeed (that is, have the string end up on clipboard), you should split the two processes, and establish the pipe via Python:

import subprocess
import shlex
p1 = subprocess.Popen(shlex.split("echo BBbb"), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p2 = subprocess.Popen(shlex.split("xsel -b"), stdin=p1.stdout)
out, err = p2.communicate()
print(out, err)

The output to this looks like:

>>> ...
>>> print(out, err)
None None

... but the string BBbb does end up on clipboard, as intended.

$\endgroup$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .