像运行交互式脚本一样运行python脚本

时间:2018-07-12 10:35:40

标签: python

出于某些文档目的,我需要运行一些python代码行,并将输出放入类的文档字符串中。

结果应如下所示:

>>> 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.]])

现在我的问题是,假设我有一个文件,里面只有几行代码,我该如何使用python运行它,以便得到这样的输出。

Bash有一个类似的选项,您可以在文件中包含以下内容,例如demo.sh

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

您可以将其作为bash -x demo.sh运行并获得以下输出:

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

是否可以使用python做同样的事情?

2 个答案:

答案 0 :(得分:2)

您可以使用code模块的InteractiveConsole类:

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))

示例运行:

~/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 $

答案 1 :(得分:0)

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]])

以下cmd将显示与从tmp.txt交互式运行cmds相同的输出

$ 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)
>>> 
相关问题