gpt4 book ai didi

python-3.x - 在 jupyter 笔记本单元格中使用单击库

转载 作者:行者123 更新时间:2023-12-03 13:33:23 25 4
gpt4 key购买 nike

有没有办法在 Jupyter 笔记本单元中使用点击库?
我想将标志传递给我的 Jupyter 笔记本代码,在笔记本中,
使其更顺畅地过渡到独立脚本。例如,使用
来自 Jupyter 笔记本单元的 OptionParser:

from optparse import OptionParser
import sys


def main():
parser = OptionParser()
parser.add_option('-f', '--fake',
default='False',
help='Fake data')
(options,args) = parser.parse_args()
print('options:{} args: {}'.format(options, args))
if options.fake:
print('Fake detected')

def test_args():

print('hello')

if __name__ == '__main__':

sys.argv = ['--fake', 'True' '--help']
main()

输出:
选项:{'假':'假'} 参数:['真--帮助']
检测到假货

使用 click 库,我收到了一系列错误。我从一个
Jupyter 笔记本单元:
import click

@click.command()
@click.option('--count', default=1, help='Number of greetings.')
@click.option('--name', prompt='Your name',
help='The person to greet.')
def hello(count, name):
"""Simple program that greets NAME for a total of COUNT times."""
for x in range(count):
click.echo('Hello %s!' % name)

if __name__ == '__main__':
hello()

输出(截断):
UnsupportedOperation                      Traceback (most recent call last)
<ipython-input-6-ad31be7bf0fe> in <module>()
12 if __name__ == '__main__':
13 sys.argv = ['--count', '3']
---> 14 hello()

~/.local/lib/python3.6/site-packages/click/core.py in __call__(self, *args, **kwargs)
720 def __call__(self, *args, **kwargs):
721 """Alias for :meth:`main`."""
--> 722 return self.main(*args, **kwargs)
723
724
...
257
258 if message:
--> 259 file.write(message)
260 file.flush()
261

UnsupportedOperation: not writable

最佳答案

您可以使用 %%python启动新 Python 进程的魔术命令:

%%python

import sys
import click

@click.command()
@click.option('--count', default=1, help='Number of greetings.')
@click.option('--name', prompt='Your name',
help='The person to greet.')
def hello(count, name):
"""Simple program that greets NAME for a total of COUNT times."""
with open('echo.txt', 'w') as fobj:
for x in range(count):
click.echo('Hello %s!' % name)

if __name__ == '__main__':
# first element is the script name, use empty string instead
sys.argv = ['', '--name', 'Max', '--count', '3']
hello()

输出:
Hello Max!
Hello Max!
Hello Max!

关于python-3.x - 在 jupyter 笔记本单元格中使用单击库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47820040/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com