1

For some documentation purposes, I need to run some lines of python code, and put the output in the docstring of the classes.

The results should look like this:

>>> from sklearn.cluster import KMeans
>>> import numpy as np
>>> X = np.array([[1, 2], [1, 4], [1, 0],
...               [4, 2], [4, 4], [4, 0]])
>>> kmeans = KMeans(n_clusters=2, random_state=0).fit(X)
>>> kmeans.labels_
array([0, 0, 0, 1, 1, 1], dtype=int32)
>>> kmeans.predict([[0, 0], [4, 4]])
array([0, 1], dtype=int32)
>>> kmeans.cluster_centers_
array([[ 1.,  2.],
       [ 4.,  2.]])

Now my question is, assuming I have a file with those few lines of code in it, how can I run it with python so that I get such an output.

Bash has a similar option where you can have the following in a file, let say demo.sh

mkdir /tmp/test1
touch /tmp/test1/1
ls /tmp/test1

And you can run it as bash -x demo.sh and get the following output:

$ bash -x /tmp/tmp.sh 
+ mkdir /tmp/test1
+ touch /tmp/test1/1
+ ls /tmp/test1
1

Is there a way I could do the same with python?

adrin
  • 4,511
  • 3
  • 34
  • 50

2 Answers2

2

You can use the code module's InteractiveConsole class:

emulate-interactive.py

import code
import sys

icon = code.InteractiveConsole()

prompt = '>>>'
for line in sys.stdin:
    line = line.rstrip()
    print(prompt, line)
    prompt = ('...' if icon.push(line) else '>>>')

test.py

import random

print(random.randint(1, 7))
print(random.randint(1, 7))
print(random.randint(1, 7))
print(random.randint(1, 7))

Example run:

~/Desktop $ python3 emulate-interactive.py < test.py
>>> import random
>>>
>>> print(random.randint(1, 7))
1
>>> print(random.randint(1, 7))
7
>>> print(random.randint(1, 7))
4
>>> print(random.randint(1, 7))
4
~/Desktop $
AKX
  • 152,115
  • 15
  • 115
  • 172
0

With the following contents in tmp.txt

$ cat tmp.txt
from sklearn.cluster import KMeans
import numpy as np
X = np.array([[1, 2], [1, 4], [1, 0],
              [4, 2], [4, 4], [4, 0]])
kmeans = KMeans(n_clusters=2, random_state=0).fit(X)
kmeans.labels_
kmeans.predict([[0, 0], [4, 4]])

the following cmd would show the same output as running cmds from tmp.txt interactively

$ python -c "import code; c=code.InteractiveConsole(); dec = lambda f: lambda x: print(x) or f(x); c.push = dec(c.push); c.interact('', '')" < tmp.txt
>>> from sklearn.cluster import KMeans
>>> import numpy as np
>>> X = np.array([[1, 2], [1, 4], [1, 0],
...               [4, 2], [4, 4], [4, 0]])
>>> kmeans = KMeans(n_clusters=2, random_state=0).fit(X)
>>> kmeans.labels_
array([0, 0, 0, 1, 1, 1], dtype=int32)
>>> kmeans.predict([[0, 0], [4, 4]])
array([0, 1], dtype=int32)
>>> 
Sunitha
  • 11,777
  • 2
  • 20
  • 23