Last active
December 16, 2015 07:39
-
-
Save battis/5400609 to your computer and use it in GitHub Desktop.
IPython Notebook Input Hack
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"metadata": { | |
"name": "input_hack" | |
}, | |
"nbformat": 3, | |
"nbformat_minor": 0, | |
"worksheets": [ | |
{ | |
"cells": [ | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": "#### Caveats\n\n* Requires at least IPython 0.13\n* Can only be called for global variables\n* Cannot be called from within another function\n\nvia [Shawn Brown](https://plus.google.com/115875830338788300419/posts/cJFqX2Rpvzn)" | |
}, | |
{ | |
"cell_type": "code", | |
"collapsed": true, | |
"input": "import IPython.core.display", | |
"language": "python", | |
"metadata": {}, | |
"outputs": [], | |
"prompt_number": 1 | |
}, | |
{ | |
"cell_type": "code", | |
"collapsed": true, | |
"input": "def ipynb_input(varname, prompt=''):\n \"\"\"Prompt user for input and assign string val to given variable name.\"\"\"\n js_code = (\"\"\"\n var value = prompt(\"{prompt}\",\"\");\n var py_code = \"{varname} = '\" + value + \"'\";\n IPython.notebook.kernel.execute(py_code);\n \"\"\").format(prompt=prompt, varname=varname)\n return IPython.core.display.Javascript(js_code)", | |
"language": "python", | |
"metadata": {}, | |
"outputs": [], | |
"prompt_number": 2 | |
}, | |
{ | |
"cell_type": "code", | |
"collapsed": false, | |
"input": "ipynb_input(varname='username',prompt='Enter your username: ')", | |
"language": "python", | |
"metadata": {}, | |
"outputs": [ | |
{ | |
"javascript": "\n var value = prompt(\"Enter your username: \",\"\");\n var py_code = \"username = '\" + value + \"'\";\n IPython.notebook.kernel.execute(py_code);\n ", | |
"output_type": "pyout", | |
"prompt_number": 3, | |
"text": "<IPython.core.display.Javascript at 0x2044ed0>" | |
} | |
], | |
"prompt_number": 3 | |
}, | |
{ | |
"cell_type": "code", | |
"collapsed": false, | |
"input": "print(username)", | |
"language": "python", | |
"metadata": {}, | |
"outputs": [ | |
{ | |
"output_type": "stream", | |
"stream": "stdout", | |
"text": "sethbattis\n" | |
} | |
], | |
"prompt_number": 4 | |
} | |
], | |
"metadata": {} | |
} | |
] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment