pass command line arguments to argv in jupyter/ipython notebook
I'm wondering if it's possible to populate sys.argv (or some other structure) with command line arguments in jupyter/ipython notebooks, similar to what is done via python scripts.
For example, if I run the python script as follows:
python test.py error
Then sys.argv will contain the parameter False. However, if I run a jupyter notebook in a similar fashion:
jupyter notebook test.ipynb False
Then the command line parameter is lost. Is there a way to access this parameter from the notebook itself?
Solution:
After a lot of looking around, I found very tedious custom library, but solved it with a few lines of code which I thought was pretty. I ended up with an html report as output using nbconvert with all the graphs in the notebook and Markdown, but accepts command line arguments via a minimal python wrapper:
python file test_args.py (normal execution of command line arguments):
import sys,osIPYNB_FILENAME = 'test_argv.ipynb'CONFIG_FILENAME = '.config_ipynb'def main(argv): with open(CONFIG_FILENAME,'w') as f: f.write(' '.join(argv)) os.system( 'jupyter nbconvert --execute {:s} --to html'.format(IPYNB_FILENAME)) return Noneif __name__ == '__main__': main(sys.argv)
The notebook contains:
import sys,os,argparsefrom IPython.display import HTMLCONFIG_FILE = '.config_ipynb'if os.path.isfile(CONFIG_FILE): with open(CONFIG_FILE) as f: sys.argv = f.read().split() else: sys .argv = ['test_args.py', 'input_file', '--int_param', '12']parser = argparse.ArgumentParser()parser.add_argument("input_file",help="Input image, directory, or npy.")parser.add_argument("--int_param", type=int, default=4, help="an optional integer parameter.")args = parser.parse_args()p = args.int_paramprint(args.input_file,p)
I can parse the python notebook for parameter parsing as usual:
python test_args.py my_input_file --int_param 12
I tend to stick the block with the argparse call into the python wrapper so that the python script catches command line errors and -h works correctly.
pass command line arguments to argv in jupyter/ipython notebook Related posts
- The most complete Java learning route in 2019, from object-oriented to enterprise-level technology, to argue against
Recently, a fan wrote me privately saying that you have written so many articles about Java technology, but you don’t understand it, but you want to learn Java programming, but I don’t know where to start. I asked if I could write some learning routes about Java. Therefore, I deliberately spent near ...
- pass command line arguments to argv in jupyter/ipython notebook
I'm wondering if it's possible to populate sys.argv (or some other structure) with command line arguments in jupyter/ipython notebooks, similar to what is done via python scripts.For example, if I run the python script as follows:python test.py errorThen sys.argv will contain the parameter False. Ho ...
- C#_.net core 3.0 custom reads .csv file data_Solve the problem that the first line is not the title_Linqtocsv improvement
  The disadvantage of the linqtocsv file is that it is impossible to set the number of lines in the title. By default, the first line is the title. Isn't this embarrassing? Not all csv files strictly write the title in the first line. The following are all data. The task I accept is to rea ...
- Some thoughts on the "arguing" of java, php and .net on the Internet!
  The debate about which java, php, and .net is good or bad has been going on for several years! For some people who really pursue technology! It is understandable that they analyze the advantages or disadvantages of the programming language they are proficient in. It is also good for ever ...
- javascript - How to pass command line arguments to Node.js program?
I have a web server written in Node.js that I want to start with a specific folder. I'm not sure how to access parameters in JavaScript. I'm running node like this:$node server.js folderHere server.js is my server code. Node.js help says this is possible:$node -hUsage: node [options] script.js [argu ...
- php-How to delete the top line (coloumn title) in the CSV file?
I have put together a script that will upload a CSV file and then extract the data into an already made table. I want to do this, so the first row (column headers) will not be inserted into the table, but the rest of the data will be.$fp = fopen($_SESSION['filename'],"r");while (($data = fgetcsv($fp ...
- cause of "org.omg.CORBA.COMM_FAILURE: vmcid: SUN minor code: 208 complete: maybe" error in my java corba chat application what is it?
I've been trying to run a Java Corba chat application Reference:- https://github.com/ehl/TalkCatIn this case, when I run the naming service ID nameserv.bat for the first time, the error message pops uporg.omg.CORBA.COMM_FAILURE: vmcid: SUN minor code: 208 completed: MaybeNaming Service active !!IOR ...
- There is no such comm target registration error in ipython
When I started the python3 notebook in the conda environment, I encountered this error in the terminal:[I 21:59:46.185 NotebookApp] Creating new notebook in /Untitled Folder[I 21:59:47.071 NotebookApp] Kernel started: a8c53aaf-8282-479d-b3ec-afb9433c30e6[IPKernelApp] ERROR | No such comm target regi ...
- java-pass Maven compiler options from the command line
I set up several projects on the continuous integration server, some of which I don’t have the right to change the source code to that server, this is a Linux machine, and I ran into a problem where the maven encoding needs to be changed to UTF8. so that it can be on the box Compile. Since I don't h ...
- c-How to pass command line parameters to c program
Since I learned to program, I have known how to write a program that accepts command line parameters. What I don’t understand is how these parameters get their value. Hope I don’t have a mixture of these two, but there is a difference between parameters and parameters. Parameters It is the value ass ...
- python - How to pass form data using Scrapy from command line?
How can I pass username and password from command line? Thanks!class LoginSpider(Spider): name = 'example.com' start_urls = ['http://www.example.com/users/login.php'] def parse(self, response): return [FormRequest.from_response(response, formdata={'username': 'john', 'password': 'secret'}, callback= ...
- Pass the command line parameters to nose
Packaging settingsI have built a Python package for testing with nose. Therefore, setup.py contains:..test_suite='nose.collector',tests_require=['nose'],..And the python setup.py test works as expected:running test...--------------------------------------------- -------------------------Ran 3 tests ...
- java – Pass the file as a command line parameter and read its line
This is the code I found on the Internet to read the file line, I also use eclipse, and pass the file name as SanShin.txt in its parameter field. But it will print:Error: textfile.txt (The system cannot find the file specified)code:public class Zip { public static void main(String[] args){ try{ // O ...
- javascript - how to pass command line arguments in NodeJS?
I have a file structure that I will enumerate for you later. I have a web server that starts a command line process when a button is pressed. I would like to add the option to run the server headless with command line arguments. Here is Is it the way I should do it? Here is my project structure./mod ...
- php-remove attribute values from product variant titles and display them on a separate line
I have a page where I want to checkout:>Remove the selected product attribute value from the product variant title item. >Also remove the quantity from the item title. >Display different product attribute values on different rows for this product variant item, such as size, color and quanti ...
- pass values into Python classes via command line
I have some code that passes variables into a script from the command line. I can pass any value to a function with var arg. The problem is that when I put the function into a class, the variable is not read into the function. The script is:import sys, osdef function(var): print varclass function_ca ...
Recent Posts
- java-Why does not show illegal forward reference error when using static variable with class name
When using the class name to access a static variable, in the code below, it does not raise a forward reference error, but it is accessed without the class name.Why doesn't this happen when using class name access?class Test{ static { System.out.println(a); // shows error a = 99; // and this line to...
- C++ Json package data view data
Take oneInput as an example in the figure:  Where is the array added to the json data package:  oneInput->value_->map_->  The arrangement order of the arrays seems to be disorderly, so the 0th array may not be the array added for the first time.  And ...
- java-How to remove authorization header in http 302 response
I am using Java/Jersy Framework (Tomcat) for REST API development. One such web service function is to redirect HTTP 302 (HTTP 302) to the S3 signed URL of a file. We use the"Authorization"header to check the request When calling this web service, the service will generate a signed URL with a signat...
- c#-How to reference GAC assembly from dynamically generated assembly?
I'm teaching myself Intermediate Language (IL) generation in C#, and I've been stuck in a dilemma for a few hours-it's almost a few days for how to reference System.Windows.Forms.dll for example) from a dynamic assembly, I use AppDomain .CurrentDomain.DefineDynamicAssembly and System.Reflection.Emit...
- javascript-cyclic reference exception in angularjs
I have the following factory definition in angularjs spa:(function () { 'use strict'; angular.module('snApp') .factory('Auth', ['$http', 'localStorageService', function ($http, localStorageService) { //code goes here }]);})();Then in my application configuration, I have the following http intercepto...
- python notes (10)--high-order functions and built-in functions
Today's content:Function small advancedlambda expressionBuilt-in functionContent review:Basic structure of functionparameterFormal parametersBasic parameters:Default parameter: def func(a1,a2=123):passNote: If the default value is an immutable type, just use it; if it is a variable type, there is a ...
- java implementation, solve.
Object-oriented:free loan repayment calculator free loan repayment. Nowadays, loans are becoming more and more humanized and convenient for end users, and banks are gradually transforming into service organizations. In addition to the traditional equal principal, equal principal and interest plan, m...
- php-packagist complains about the new package InvalidArgumentException
The first package I made for a composer in the packager. I actually wrote it for my own project, but I can’t use it anywhere!When i docomposer require wearede/tbcpay-phpIt complains[InvalidArgumentException] Could not find package wearede/tbcpay-php at any version for your minimum-stability (stable)...
- The latest Java senior development engineer interview syllabus
Currently, there are books similar to"Java XX Collection"on the market, and the contents of the books focus on explaining the most basic parts of Java. The most serious thing is that there are a lot of wrong contents, which are extremely misleading. In addition, there are also various Java interview...
- Cao Gong said Spring Boot source code (19) - The tool that Spring brings us, don’t worry about creating a proxy (ProxyFactory)
Words written in the frontRelated background and resources:Mr. Cao said the Spring Boot source code (1) - What is Bean Definition, with a spring mind map to shareMr. Cao said the Spring Boot source code (2) - What exactly is Bean Definition? Let's explain each method to the interface.Mr. Cao said Sp...