Ipython Jupyter Notebook中有一个有趣的选项,可以直接从笔记本执行命令行语句。例如:
! mkdir ...
! python file.py
此外,可以使用以下代码运行此代码os
:
import os
os.system('cmd command')
但是如何运行交互式shell命令。例如:
!conda install package
可能需要将来输入([Y]/N
)或文件夹位置,但不接受其他输入。
假设您正在询问交互性,可以尝试一些方法。
如果您想知道Jupyter如何知道单元格的输出何时结束:好吧,它显然不知道,它只是将捕获的输出转储到最近活动的单元格中:
import threading,time
a=5
threading.Thread(target=lambda:[print(a),time.sleep(20),print(a)]).start()
(故意短于示例,因为这只是辅助信息。在等待20秒的过程中,您有时间激活另一个单元格,可能是通过发出a=6
)
这可以用于将某些控制台代码的输出输出到屏幕,同时从主线程控制它:
import sys,threading,subprocess
proc=subprocess.Popen('/bin/sh',stdout=subprocess.PIPE,stdin=subprocess.PIPE,stderr=subprocess.STDOUT)
pout=proc.stdout
pin=proc.stdin
def outLoop():
running=True
while(running):
line=pout.readline().decode(sys.stdout.encoding)
print(line,end='')
running='\n' in line
print('Finished')
threading.Thread(target=outLoop).start()
然后,您可以发出命令,例如
pin.write(b'ls -l\n')
pin.flush()
和
pin.write(b'exit\n')
pin.flush()
即使b'ls\nexit\n'
有效,这就是为什么要花outLoop
这么长的时间(一个简单的while(proc.poll() is None)
- print(...)
循环比获取所有输出要早完成。
然后整个事情可以自动化为:
while(proc.poll() is None):
inp=bytearray(input('something: ')+'\n',sys.stdin.encoding)
if(proc.poll() is None):
pin.write(inp)
pin.flush()
这在https://try.jupyter.org/上很好用,但是显然我不想在那儿安装conda软件包,所以我不知道当conda提出问题时会发生什么。
幸运的是,输入字段位于单元格的底部(已测试ls;sleep 10;ls
)。一个不幸的事情是,输入字段需要在最后一个额外的条目消失(这已经是“好”的方式,当它是一个简单的while(...)
- write(bytearray(input()))
- flush()
3内胆,它与一个异常退出。
如果有人想在Windows上尝试此功能,则可以使用'cmd'
,但我建议使用硬编码'windows-1252'
而不是sys.stdin/out.encoding
:他们说的是UTF-8,但是一个简单的dir
命令已经产生了既不是UTF-8也不是ASCII的输出(大小为3位的组是一个0xA0字符)。或者只是删除decode
零件(并使用running=0xA in line
)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句