pythonbashjupyterqtconsole

Launch external jupyter qtconsole and run a script with args


I have a script which takes one argument to run. Usually, I can run it from terminal using the standard python console with the following command:

$python3 myscript.py arg1 &

But I want to execute the script in jupyter qtconsole. It is possible to launch an external console from the terminal with this command:

$jupyter qtconsole &

I tried to launch jupyter qtconsole and run myscript.py with an argument arg1, using a similar approach:

$jupyter qtconsole myscript.py arg1 &

But it didn't worked. Is it possible to do this? How?


Solution

  • From a new qtconsole:

    In [14]: sys.argv
    Out[14]: 
    ['/usr/local/lib/python3.5/dist-packages/ipykernel/__main__.py',
     '-f',
     '/run/user/1000/jupyter/kernel-25521.json']
    
    In [16]: %connect_info
    {
      "stdin_port": 57643,
      "key": "bcc03e84-7c43-4fbe-84d7-6c005aa37930",
      "ip": "127.0.0.1",
      "transport": "tcp",
      "iopub_port": 45064,
      "hb_port": 46748,
      "control_port": 39960,
      "kernel_name": "",
      "shell_port": 57532,
      "signature_scheme": "hmac-sha256"
    }
    
    Paste the above JSON into a file, and connect with:
        $> jupyter <app> --existing <file>
    or, if you are local, you can connect with just:
        $> jupyter <app> --existing kernel-25521.json
    or even just:
        $> jupyter <app> --existing
    if this is the most recent Jupyter kernel you have started.
    

    So following that if I don

    $ jupyter console --existing kernel-25521.json
    

    I get a console that shares the kernel with the qtconsole. If I import a module or create a variable in one, it is available in the other.

    Usually when I want to run a script in ipython I use the %run magic rather than trying to include it in command line.

    In [32]: %run echo_argv.py testing 1 2 3
    ['echo_argv.py', 'testing', '1', '2', '3']
    

    Instead of the shell

    $ipython3 -i echo_argv.py -- testing 1 2 3
    

    To run a script without any further interaction, I use the regular $python invocation. No need to involve jupyter or ipython.

    $ python3 echo_argv.py -- testing 1 2 3
    

    From the qtconsole config options:

    KernelManager.kernel_cmd : List Default: []

    DEPRECATED: Use kernel_name instead.

    The Popen Command to launch the kernel. Override this if you have a custom kernel. If kernel_cmd is specified in a configuration file, Jupyter does not pass any arguments to the kernel, because it cannot make any assumptions about the arguments that the kernel understands. In particular, this means that the kernel does not receive the option –debug if it given on the Jupyter command line.