在Jupyter的同一行上交替运行Shell和Python命令

时间:2019-01-07 12:39:31

标签: python ipython jupyter

如何在同一行交替执行一连串的python和shell命令? 有没有办法在Python表达式中嵌入魔术?

例如:

var = !date +%s <<command to stop magic execution>> [0]

我现在的做法:

var = !date +%s
var = var[0]

1 个答案:

答案 0 :(得分:0)

An equivalent that works in all Python interpreters, whether or not Jupyter is active, would be:

import subprocess
def shell(args):
    return subprocess.Popen(args, stdout=subprocess.PIPE, shell=True).communicate()[0].split('\n')

var = shell('date +%s')[0]

...that said, for the specific use case, you don't need it:

import time
var = str(int(time.time()))

will calculate the same value with far less overhead. (And if you don't want the side effects such as rounding to the nearest second or converting to a string, the needed changes will be obvious).