Windows starts jupyter with one click

Windows starts jupyter with one click

Introduction to jupyter

Jupyter is an open source interactive computing environment, mainly used for data analysis, data visualization and scientific computing. Its name comes from an acronym for three programming languages: Julia, Python, and R, all of which can run in the Jupyter environment. If you want to do tasks like data analysis, scientific computing, machine learning, etc., Jupyter is a very useful tool because it provides an interactive environment where you can explore data, write code, and see the results in real time.

Key features of Jupyter

interactivity

The Jupyter environment allows users to write and execute code interactively. Users can execute a piece of code or a block of code at a time and see the results immediately. This is very useful for data analysis and exploratory programming.

Support multiple programming languages

Although initially supporting Julia, Python, and R, Jupyter can actually support many programming languages. Users can extend Jupyter's language support by installing the corresponding kernel.

Notebook document

Jupyter Notebook is a file format for the Jupyter environment that allows users to mix executable code, visual output, text descriptions, formulas, and images in the same document. This makes Jupyter a great tool for sharing and presenting analysis processes.

data visualization

The Jupyter environment is embedded with rich data visualization tools, allowing users to easily create charts, images, and animations to better understand data.

flexibility

Jupyter can be installed and run on a local computer, or deployed on a cloud server. This allows users to choose a suitable operating environment according to their needs.

Jupyter installation

Install Jupyter Notebook on Linux

  1. Install Python: Most Linux distributions come with Python, you can check if it is installed with the following command:

    python --version
    

    If Python is not installed or requires a newer version, install or update it using the appropriate package management tool for your distribution.

  2. Install pip: If pip is not installed, you can install it with the following command:

    sudo apt-get update
    sudo apt-get install python3-pip
    
  3. Install Jupyter Notebook: Run the following command in Terminal to install Jupyter Notebook:

    python3 -m pip install jupyter
    
  4. Start Jupyter Notebook: Run the following command in Terminal to start Jupyter Notebook:

    jupyter notebook
    

Install Jupyter Notebook on Windows

  1. Install Python and pip: You can download the Python installer from the Python official website (https://www.python.org/downloads/windows/), and make sure to check the "Add Python to PATH" option.

  2. Install Jupyter Notebook: Run the following command in Command Prompt to install Jupyter Notebook:

    python -m pip install jupyter
    
  3. Start Jupyter Notebook: Run the following command in the command prompt to start Jupyter Notebook:

    jupyter notebook
    

To sum up, whether it is linux or windows installation, there are a few steps:

   1. 首先安装python环境,windows则配置一下环境
   2. 再安装pip环境
   3. 通过pip命令安装jupyter模块
   4. 运行jupyter

How to start and install jupyter with the next key on windows?

Background (why do you want to do this?)

The actual situation is that we want to be an online python editor, which requires users to program python online in a browser and output the results of python code execution in real time. Some people may say why not directly execute the python command on the server through the code to execute the python code, but in fact, it is impossible to return the execution result in real time, such as a for loop printing cannot be realized, such as the user needs to input, after accepting the input Show output.

Design ideas (how to do it?)

question

  • windowsImplementation Opinion Installation is generally a exeprogram that clicks one button to start. How to package it exe?
  • How to start the environment for installation pythonandpip

Solve the problem

  1. At present, exethere are generally two ways of packaging: use pyinstallerthe package Pythonprogram as .exeand use Visual Studiothe package C#program as .exe, here we pythonare more familiar with the code, choose to usepyinstaller
  2. First of all, if pythonsome are installed through code , the experience is very bad, and users need to click to install. Here we change our thinking and find a package that provides a free installation version on the official website .windowspythonpython.exepythonpython

Don't be too happy too early, the free version of pythonthe package does not have pipmodules, so you have to consider installing pipmodules. pythonFor the installation pipmodule, see: Installation-free version python installs pip module .

Summarize

Let's summarize the previous ideas and carry out a more detailed design idea:

  1. Download the official pythonand unzip it, and get-pip.pyput it into pythonthe folder
  2. First determine pythonwhether it has been installed, if not installed, configure pythonthe environment variable
  3. First determine pipwhether the module has been installed, if not installed, pythoninstall the pip module through the code
  4. After the module is installed pip, configure pipthe environment variable
  5. In order to prevent the installation jupyterfrom overtime, pythonreplace the mirror source with the domestic mirror source by code
  6. pipInstall usingjupyter
  7. start upjupyter

This step is the complete code logic. In fact, it is not complete here, because you have installed it , and you definitely don’t want to click to start it jupyterevery time you use it , so you need to do a boot-up self-starting, which will be reduced to How to do boot automatically.exejupyterwindows

Code

jupyter packaging exe code implementation

jupyter.py

import os
import subprocess
import traceback
import socket
from utils.logutils import log

python_path = "python"
scripts_path = "python\Scripts"


def is_installed(model):
    try:
        # 尝试运行 python 命令
        result = subprocess.run([model, "--version"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        # 检查返回结果
        if result.returncode == 0:
            return True
        else:
            return False
    except FileNotFoundError:
        return False


def install_pip_module():
    if not is_installed("pip"):
        # 安装 pip 模块
        try:
            new_path = os.path.join(os.getcwd(), f'python')
            subprocess.check_call(["python", f'{
      
      new_path}\get-pip.py'])
            log.info("成功安装 pip 模块")
        except subprocess.CalledProcessError:
            log.info("安装 pip 模块时出错")


def configure_path(path):
    # Assuming the path to add is '/path/to/python/bin'
    new_path = os.path.join(os.getcwd(), f'{
      
      path}')
    # 获取当前的PATH环境变量
    current_path = os.environ["PATH"]
    # 在当前的PATH后追加新路径,并使用os.pathsep分隔
    new_path_value = current_path + os.pathsep + new_path
    # 更新环境变量
    os.environ["PATH"] = new_path_value


def configure_path_env_variable():
    if not is_installed("pip") and is_installed("python"):
        env_var_name = "PATH"
        python_path = os.path.join(os.getcwd(), f'python')
        scripts_path = os.path.join(os.getcwd(), f'python\Scripts')
        env_var_value = python_path + os.pathsep + scripts_path
        try:
            # 设置环境变量
            configure_path(f'python')
            configure_path(f'python\Scripts')
            subprocess.check_call(["setx", env_var_name, f"%{
      
      env_var_name}%;{
      
      env_var_value}"])
            log.info(f"成功追加环境变量: {
      
      env_var_name}={
      
      env_var_value}")
        except subprocess.CalledProcessError:
            log.info(f"追加环境变量时出错: {
      
      env_var_name}")


def change_mirror_source():
    if not is_installed("pip"):
        # 更换镜像源pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple
        mirror_url = "https://pypi.tuna.tsinghua.edu.cn/simple"
        os.system('pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple')
        log.info(f"已更换镜像源:{
      
      mirror_url}")


def install_jupyter():
    if not is_installed("jupyter"):
        # 使用 pip 安装 jupyter
        try:
            subprocess.check_call(["python", "-m", "pip", "install", "jupyter_kernel_gateway"])
            log.info("成功安装 Jupyter")
        except subprocess.CalledProcessError:
            log.info("安装 Jupyter 时出错")


def start_jupyter():
    # 启动 Jupyter  start /B jupyter kernelgateway
    cmd = ['jupyter', 'kernelgateway', '--KernelGatewayApp.ip=0.0.0.0', '--KernelGatewayApp.port=18012',
           '--KernelGatewayApp.allow_credentials=*', '--KernelGatewayApp.allow_headers=*',
           '--KernelGatewayApp.allow_methods=*', '--KernelGatewayApp.allow_origin=*']
    try:
        subprocess.Popen(cmd, creationflags=subprocess.CREATE_NEW_CONSOLE, shell=True)
        log.info("Jupyter kernel gateway 启动成功")
    except OSError as error:
        log.error(error)


def is_running():
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.settimeout(3)
        result = s.connect_ex(('127.0.0.1', 18012))
        s.close()
        if result == 0:
            log.info("AI-Link.exe is already running or port conflict!")
            return True
        else:
            return False
    except:
        log.info("Exception of is_running:{0}".format(traceback.format_exc()))
        return False


def main_process():
    if not is_running():
        # 配置环境变量
        configure_path_env_variable()
        # 安装pip模块
        install_pip_module()
        # 更换镜像源
        change_mirror_source()
        # 使用pip进行安装jupyter
        install_jupyter()
        # 启动jupyter
        start_jupyter()


if __name__ == "__main__":
    main_process()

logutils.py

# -*- coding: utf-8 -*-
import time
import win32api
import win32con


class Log(object):
    def write(self, level, msg):
        date = time.strftime("%Y-%m-%d", time.localtime())
        log_file = r"{0}{1}{2}".format( "jupyter.", date, ".log")
        line = "{0} {1} {2}\n".format(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), level, msg)
        with open(log_file, 'a', encoding='utf-8') as f:
            f.write(line)

    def info(self, msg):
        self.write("INFO", msg)

    def error(self, msg):
        self.write("ERROR", msg)

    @staticmethod
    def notice_info(msg: str):
        win32api.MessageBox(0, f"{
      
      msg}", "警告", win32con.MB_ICONWARNING)


log = Log()

jupyter Package exeto achieve windowsself-start

train of thought
  1. First of all, we must understand windowshow to realize the boot-up self-starting
  2. How to pythonpackage exethe program through code to realize booting automatically
solution

1. To Windowsautomatically start the program at startup .exe, you can set it in the following ways:

  1. Add a program shortcut to the startup folder :
    • Press Win + Rthe key to open the "Run" dialog box.
    • Enter shell:startupand press enter, this will open the current user's startup folder.
    • To create a program shortcut in the startup folder, you can right-click the program .exefile, then select "Send to" -> "Desktop (create shortcut)", and then drag and drop the generated shortcut to the startup folder.
  2. Registry editor :
    • Press Win + Rthe key to open the "Run" dialog box.
    • Type regeditand press Enter to open the Registry Editor.
    • Navigate to HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run.
    • Right-click on the blank space on the right and select "New" -> "String Value".
    • Name the new string value whatever you want, and then modify its value data to be the full path of the program, eg C:\path\to\your\program.exe.
  3. Task Scheduler :
    • Search for and open Task Scheduler.
    • On the left navigation bar, choose Create Basic Task.
    • Follow the instructions of the wizard, set the task name and trigger conditions, and select "Start Program" as the operation type.
    • Specify the path to the program to start, and then complete the task creation process.

The above three methods can realize self-starting at boot. Let’s first look at the second solution, which needs to modify the registry. In theory, the code is feasible. The third solution needs to design a task plan, which is relatively less feasible through code, and then look at the first one. For all windowssystems, startupthe file directory is relatively fixed, and you only need to create a shortcut, which is relatively simple, so we adopt the first solution.

2. Realize opening and self-starting through code

The code implementation is feasible, but the main problem is that if the exe is not executed with administrator privileges, it is necessary to forcibly obtain the following adminadministrator privileges.

Code:

installer.py

# -*- coding: utf-8 -*-
import os
import traceback
import ctypes
import sys
import win32com.client as client

shell = client.Dispatch("WScript.Shell")
from utils.logutils import log


def is_admin():
    try:
        return ctypes.windll.shell32.IsUserAnAdmin()
    except Exception as e:
        log.error(e)
        return False


def create_shortcut():
    try:
        filename = os.path.join(os.getcwd(), f'jupyter.exe')
        lnkName = f"C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp\jupyter.lnk"
        shortcut = shell.CreateShortCut(lnkName)
        shortcut.TargetPath = filename
        shortcut.save()
    except:
        log.info("Exception of creating a shortcut:{0}".format(traceback.format_exc()))


def jupyter_installer():
    if is_admin():
        create_shortcut()  # 配置自启动服务
    else:
        ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, __file__, None, 1)


if __name__ == '__main__':
    try:
        jupyter_installer()
    except:
        log.info("Service initialization failed:{0}".format(traceback.format_exc()))

pyinstaller package exe

pyinstaller -F install.py
pyinstaller -F jupyter.py

Source address and packaged exefiles

source address path

https://github.com/LBJWt/windows-jupyter

The download address of the packaged complete exe file

https://download.csdn.net/download/wagnteng/88245132

Guess you like

Origin blog.csdn.net/wagnteng/article/details/132457241