[英]Run python script as if it was run interactively
For some documentation purposes, I need to run some lines of python code, and put the output in the docstring of the classes. 出于某些文档目的,我需要运行一些python代码行,并将输出放入类的文档字符串中。
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. 现在我的问题是,假设我有一个文件,里面只有几行代码,我该如何用
python
运行它,以便得到这样的输出。
Bash has a similar option where you can have the following in a file, let say demo.sh
Bash有一个类似的选项,您可以在文件中包含以下内容,例如
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 demo.sh
运行,并获得以下输出:
$ 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
? 有没有办法可以用
python
做同样的事情?
You can use the code
module's InteractiveConsole
class: 您可以使用
code
模块的InteractiveConsole
类:
emulate-interactive.py 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 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 $
With the following contents in tmp.txt 在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 以下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)
>>>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.