整合營銷服務商

          電腦端+手機端+微信端=數據同步管理

          免費咨詢熱線:

          PyScript:讓Python在HTML中運行

          家好,我是DD,已經是封閉在家的第51天了!

          最近一直在更新Java新特性(https://www.didispace.com/java-features/)和IDEA Tips(https://www.didispace.com/idea-tips/)兩個原創專欄,其他方向內容的動態關注少了。昨天天晚上刷推的時候,瞄到了這個神奇的東西,覺得挺cool的,拿出來分享下:

          相信你看到圖,不用我說,你也猜到是啥了吧?html里可以跑python代碼了

          看到好多Python公眾號已經開始猛吹未來了,但乍看怎么覺得有點像JSP?或者一些模版引擎?是進步還是倒退呢?與其瞎想,不如仔細看看這個東東的能力吧!

          根據官方介紹,這個名為PyScript的框架,其核心目標是為開發者提供在標準HTML中嵌入Python代碼的能力,使用 Python調用JavaScript函數庫,并以此實現利用Python創建Web應用的功能。

          看到介紹里提到了調用JavaScript函數庫的能力,看來跟JSP或者模版引擎還是有區別的。

          PyScript 快速體驗

          官方給了一個例子,可以幫助我們觀的感受這個開發框架的能力,不妨跟著DD看看,它能做啥吧!

          第一個案例,hello world

          代碼很簡單,就下面這幾行。你只需要創建一個html文件,然后復制進去就可以了。

          <html>
            <head>
              <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
              <script defer src="https://pyscript.net/alpha/pyscript.js"></script>
            </head>
            <body> 
              <py-script> 
                  print('Hello, World!') 
              </py-script> 
            </body>
          </html>
          

          保存好之后,在瀏覽器里打開就能看到這樣的頁面了:

          回頭再看看這個html里的內容,三個核心內容:

          • 引入pyscript的樣式文件:<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
          • 引入pyscript的腳本文件:<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
          • <py-script>標簽中寫具體的python代碼來輸出Hello World

          如果你懶得自己敲代碼的話,本文的兩個案例代碼我打包放在公眾號了,需要的朋友可以關注公眾號“程序猿DD”,回復:pyscript 獲取。

          第二個案例,數據定義 + 數據展示

          先創建一個data.py文件,然后加入前面的代碼。功能很簡單,就是隨機生成(x,y)的坐標

          import numpy as np
          
          def make_x_and_y(n):
              x = np.random.randn(n)
              y = np.random.randn(n)
              return x, y
          

          再創建一個html文件,加入下面的代碼

          <html>
              <head>
                <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
                <script defer src="https://pyscript.net/alpha/pyscript.js"></script>
                <py-env>
                  - numpy
                  - matplotlib
                  - paths:
                    - /data.py
                </py-env>
              </head>
          
            <body>
              <h1>Let's plot random numbers</h1>
              <div id="plot"></div>
              <py-script output="plot">
              import matplotlib.pyplot as plt
              from data import make_x_and_y
          
              x, y = make_x_and_y(n=1000)
          
              fig, ax = plt.subplots()
              ax.scatter(x, y)
              fig
              </py-script>
            </body>
          </html>
          

          這里就稍微復雜一些了,除了hello world中的幾個要點外,這里還有這幾個要關注的地方:

          • <py-env>標簽:這里聲明要引入的包和要引入的文件(上面創建的data.py
          • <py-script output="plot">:這里定義了要在<div id="plot"></div>中輸出的內容,可以看到這里的邏輯都是用python寫的

          這個頁面的執行效果是這樣的:

          是不是很神奇呢?整個過程中都沒有大家熟悉的cs、js內容,就完成了這樣一個圖的頁面實現。

          小結

          最后,談談在整個嘗試過程中,給我的幾個感受:

          1. 開發體驗上高度統一,對于python開發者來說,開發Web應用的門檻可以更低了
          2. 感覺性能上似乎有所不足,幾個復雜的案例執行有點慢,開始以為是部分國外cdn的緣故,后來移到本地后,還是慢。這部分可能還需要進一步優化。

          這個開發框架目前還只是alpha版本,未來一定還會有更多特性與優化出來,總體上我覺得這個框架還是非常cool的,尤其對于剛學會Python,或者只會Python,但又想快速開發Web應用的小伙伴來說,可能將會是個不錯的選擇,那你覺得這個框架如何?未來會不會火?留言區聊聊吧!

          數字的游戲

          根據官方教程,照寫一個程序,來體驗一下rust的程序開發過程。

          需求

          游戲很簡單, 就是一次次輸入比對預先生成的隨機數。

          1. 隨機產生一個數字
          2. 讓用戶輸入,并比對大小,給出提示
          3. 直到猜中數字。

          涉及到的知識點

          1. cargo 引入隨機數包
          2. 基本的rust語句使用,基本的rust的函數使用。
          3. 了解工程從搭建到編寫到編譯生成的完成過程。

          開始

          Cargo是rust的包管理工具, 對于本需求需要rand的方法, 但是該方法再rust中并不存在, 所以通過Cargo引入了第三方包的方式進行使用。

          Cargo 說明

          Cargo 不僅僅是一個包管理器,同時還是Rust項目的管理工具。

          可以通過cargo的幫助信息查看命令以及功能說明. cargo -h

           Rust's package manager
           
           Usage: cargo [+toolchain] [OPTIONS] [COMMAND]
                  cargo [+toolchain] [OPTIONS] -Zscript <MANIFEST_RS> [ARGS]...
           
           Options:
             -V, --version             Print version info and exit
                 --list                List installed commands
                 --explain <CODE>      Provide a detailed explanation of a rustc error message
             -v, --verbose...          Use verbose output (-vv very verbose/build.rs output)
             -q, --quiet               Do not print cargo log messages
                 --color <WHEN>        Coloring: auto, always, never
             -C <DIRECTORY>            Change to DIRECTORY before doing anything (nightly-only)
                 --frozen              Require Cargo.lock and cache are up to date
                 --locked              Require Cargo.lock is up to date
                 --offline             Run without accessing the network
                 --config <KEY=VALUE>  Override a configuration value
             -Z <FLAG>                 Unstable (nightly-only) flags to Cargo, see 'cargo -Z help' for details
             -h, --help                Print help
           
           Commands:
               build, b    Compile the current package
               check, c    Analyze the current package and report errors, but don't build object files
               clean       Remove the target directory
               doc, d      Build this package's and its dependencies' documentation
               new         Create a new cargo package
               init        Create a new cargo package in an existing directory
               add         Add dependencies to a manifest file
               remove      Remove dependencies from a manifest file
               run, r      Run a binary or example of the local package
               test, t     Run the tests
               bench       Run the benchmarks
               update      Update dependencies listed in Cargo.lock
               search      Search registry for crates
               publish     Package and upload this package to the registry
               install     Install a Rust binary. Default location is $HOME/.cargo/bin
               uninstall   Uninstall a Rust binary
               ...         See all commands with --list
           
           See 'cargo help <command>' for more information on a specific command.

          可以通過cargo --list查看所提供的命令

           Installed Commands:
               add                  Add dependencies to a Cargo.toml manifest file
               b                    alias: build
               bench                Execute all benchmarks of a local package
               build                Compile a local package and all of its dependencies
               c                    alias: check
               check                Check a local package and all of its dependencies for errors
               clean                Remove artifacts that cargo has generated in the past
               clippy               Checks a package to catch common mistakes and improve your Rust code.
               config               Inspect configuration values
               d                    alias: doc
               doc                  Build a package's documentation
               fetch                Fetch dependencies of a package from the network
               fix                  Automatically fix lint warnings reported by rustc
               fmt                  Formats all bin and lib files of the current crate using rustfmt.
               generate-lockfile    Generate the lockfile for a package
               git-checkout         This command has been removed
               help                 Displays help for a cargo subcommand
               init                 Create a new cargo package in an existing directory
               install              Install a Rust binary. Default location is $HOME/.cargo/bin
               locate-project       Print a JSON representation of a Cargo.toml file's location
               login                Log in to a registry.
               logout               Remove an API token from the registry locally
               metadata             Output the resolved dependencies of a package, the concrete used versions including overrides, in machine-readable format
               miri
               new                  Create a new cargo package at <path>
               owner                Manage the owners of a crate on the registry
               package              Assemble the local package into a distributable tarball
               pkgid                Print a fully qualified package specification
               publish              Upload a package to the registry
               r                    alias: run
               read-manifest        Print a JSON representation of a Cargo.toml manifest.
               remove               Remove dependencies from a Cargo.toml manifest file
               report               Generate and display various kinds of reports
               rm                   alias: remove
               run                  Run a binary or example of the local package
               rustc                Compile a package, and pass extra options to the compiler
               rustdoc              Build a package's documentation, using specified custom flags.
               search               Search packages in crates.io
               t                    alias: test
               test                 Execute all unit and integration tests and build examples of a local package
               tree                 Display a tree visualization of a dependency graph
               uninstall            Remove a Rust binary
               update               Update dependencies as recorded in the local lock file
               vendor               Vendor all dependencies for a project locally
               verify-project       Check correctness of crate manifest
               version              Show version information
               yank                 Remove a pushed crate from the index

          Cargo中,每個命令均可通過-help的方式來查看具體命令的用法, 例如:cargo run -help

          較為常用的如下:

          • cargo build :編譯當前項目
          • cargo check:分析當前項目并報告,但不產出文件
          • cargo run:執行src/main.rs
          • Cargo clear:移除當前項目的target目錄
          • Cargo update:更新當前項目中的依賴
          • cargo new: 創建一個新工程。

          cargo 創建rust項目

          作為包管理工具,cargo可以下載第三方庫。

          同時cargo 也可以用來建立自己的rust項目, 包括可行性程序以及庫。

          可以通過

          cargo new project_name -bin 創建一個rust程序

          cargo new project_name --lib 創建一個庫

          cargo 庫

          再rust 第三方庫叫crates, 可以通過https://crates.io/上找到。

          本例子中使用rand, 可以找到該庫文件。



          開始建立工程

          工程建立一些代碼的編寫, 本章節不做細節描述。 概要說明一下

          建立工程

           $ cargo new guess-game-app
           Created binary (application) `guess-game-app` package
           $ cd guess-game-app

          加入依賴

          修改toml文件,加入rand依賴

           [package]
           name = "guess-game-app"
           version = "0.1.0"
           edition = "2021"
           
           # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
           
           [dependencies]
           rand="0.8.5"

          編譯

          編譯cargo buildcargo check

          引入包后,習慣的執行編譯, 會導入對應的包文件。

               Updating crates.io index
             Downloaded rand_chacha v0.3.1
             Downloaded cfg-if v1.0.0
             Downloaded ppv-lite86 v0.2.17
             Downloaded rand_core v0.6.4
             Downloaded getrandom v0.2.11
             Downloaded rand v0.8.5
             Downloaded libc v0.2.150
             Downloaded 7 crates (910.0 KB) in 4.23s
              Compiling libc v0.2.150
              Compiling cfg-if v1.0.0
              Compiling ppv-lite86 v0.2.17
              Compiling getrandom v0.2.11
              Compiling rand_core v0.6.4
              Compiling rand_chacha v0.3.1
              Compiling rand v0.8.5
              Compiling guess-game-app v0.1.0 (/Users/zhuchunlei/work/08_rust/guess-game-app)
               Finished dev [unoptimized + debuginfo] target(s) in 12.11s

          源碼

          修改源文件,src/main.rs(代碼來源教程中,目前為止只是照著敲, 具體含義再逐漸學習理解)

           use rand::Rng;
           use std::cmp::Ordering;
           use std::io;
           
           fn main() {
               println!("Guess the number!");
           
               let secret_number = rand::thread_rng().gen_range(1..=100);
           
               loop {
                   println!("Please input your guess.");
           
                   let mut guess = String::new();
           
                   io::stdin()
                       .read_line(&mut guess)
                       .expect("Failed to read line");
           
                   let guess: u32 = match guess.trim().parse() {
                       Ok(num) => num,
                       Err(_) => continue,
                   };
           
                   println!("You guessed: {guess}");
           
                   match guess.cmp(&secret_number) {
                       Ordering::Less => println!("Too small!"),
                       Ordering::Greater => println!("Too big!"),
                       Ordering::Equal => {
                           println!("You win!");
                           break;
                       }
                   }
               }
           }

          編譯執行

          序員寶藏庫:https://gitee.com/sharetech_lee/CS-Books-Store

          你想要的,這里都有!

          作為程序員用的比較多的工具是什么?

          我覺得搜索引擎絕對能名列前茅。

          在開發過程中,總會遇到這樣或者那樣的問題超出我們自身的知識范圍。這些問題可能是編程語言方面的,可能是Linux操作系統方面的,可能是服務部署方面的等等。

          當遇到這種問題時,很多同學會選擇求助于搜索引擎,懂得懂得,搜索引擎搜出的很多結果要么和問題無關、要么是個大坑。

          所以,從事開發工作這么多年,我深刻意識一個道理,能夠快速解決問題真的是一項非常突出的本領,哪怕是在借助于互聯網的情況下。

          話說回來,正是因為尋求問題的道路非常曲折繁瑣,因此,網上出現了各種各樣的速查表「CheatSheet」,估計有不少同學過去都看到過很多了。

          但是,我認為這并沒有從效率上徹底解決問題。

          今天我在瀏覽Github時發現一款非常不錯的開源工具,真的讓我眼前一亮。

          這款開源工具的名字叫做cheat.sh,目前已經33K+ Star了。

          這款工具的簡潔是「你唯一需要的速查表」,簡單概括,這款工具把知名、權威社區的答案、資料進行了統一匯總,我們只需要這一款工具就可以快速得到最準確、最可靠的答案。

          它背后的知識來源于tldr、StackOverflow、cheat.sheets等社區或者開源項目。

          為了更加清晰的理解它的用處,下面先來看一個示例:

          $ curl cht.sh/lua/table+keys
              -- lua: retrieve list of keys in a table
          
              local keyset={}
              local n=0
          
              for k,v in pairs(tab) do
                n=n+1
                keyset[n]=k
              end
          
              --[[
                 [ Note that you cannot guarantee any order in keyset. If you want the
                 [ keys in sorted order, then sort keyset with table.sort(keyset).
                 [ 
                 [ [lhf] [so/q/12674345] [cc by-sa 3.0]
                 ]]

          上面執行的curl命令包含下面幾個信息:

          • cht.sh:工具名稱
          • lua:編程語言
          • table+keys:要查詢的問題,多個關鍵詞用加好鏈接

          通過這樣,它就可以快速在終端下給出問題的答案。

          如果你不想要文字描述,只想要「純凈」的答案,還可以通過參數來處理:

           $ curl cht.sh/lua/table+keys\?Q
              local keyset={}
              local n=0
          
              for k,v in pairs(tab) do
                n=n+1
                keyset[n]=k
              end

          想必到這里,很多同學都已經知道它的用法了,概括一下這款工具的價值,主要有以下幾點:

          • 簡潔——它應該只包含你需要的東西,沒有雜亂的信息
          • 快速——能夠快速得到問題的答案,「所見即所得」
          • 全面——編程語言、操作系統等等,覆蓋面非常全
          • 通用——隨時隨地可用,

          可能很多同學還有一絲疑慮,感覺用curl每次都要輸入很長的命令,太麻煩。

          沒事,前面只是一個小示例,下面系統的介紹一下如何安裝并使用客戶端。

          安裝

          方式1

          PATH_DIR="$HOME/bin"  # or another directory on your $PATH
          mkdir -p "$PATH_DIR"
          curl https://cht.sh/:cht.sh > "$PATH_DIR/cht.sh"
          chmod +x "$PATH_DIR/cht.sh"

          方式二

          curl -s https://cht.sh/:cht.sh | sudo tee /usr/local/bin/cht.sh && sudo chmod +x /usr/local/bin/cht.sh

          安裝后就可以在終端下使用了。

          如果想用交互式命令模式,還需要通過命令sudo apt install rlwrap安裝rlwrap。

          用法

          通過上述命令安裝客戶端之后,就不用再像前面curl命令那樣每次輸入很長的命令,可以用更加貼近人為描述的方式查詢問題答案。

          舉幾個例子:

          $ cht.sh go reverse a list
          $ cht.sh python random list elements
          $ cht.sh js parse json

          這樣看,估計很多開發同學都能夠懂得它的用法了,「命令+語言+問題」。

          可以看看效果:

          $ cht.sh python random number
          #  Try:
          
           from random import randrange
           print(randrange(10))
          
          #  **Docs:**
          #  https://docs.python.org/3/library/random.htmlrandom.randrange
          #  
          #  [kovshenin] [so/q/3996904] [cc by-sa 3.0]

          再嘗試一個:

          $ cht.sh python matplotlib plot line
          #  You can directly plot the lines you want by feeding the `plot` command
          #  with the corresponding data (boundaries of the segments):
          #  
          #  `plot([x1, x2], [y1, y2], color='k', linestyle='-', linewidth=2)`
          #  
          #  (of course you can choose the color, line width, line style, etc.)
          #  
          #  From your example:
          
           import numpy as np
           import matplotlib.pyplot as plt
          
           np.random.seed(5)
           x = np.arange(1, 101)
           y = 20 + 3 * x + np.random.normal(0, 60, 100)
           plt.plot(x, y, "o")
          
           # draw vertical line from (70,100) to (70, 250)
           plt.plot([70, 70], [100, 250], 'k-', lw=2)
          
           # draw diagonal line from (70, 90) to (90, 200)
           plt.plot([70, 90], [90, 200], 'k-')
          
           plt.show()
          
          #  ![new chart](https://i.imgur.com/76drc.png)
          #  
          #  [gcalmettes] [so/q/12864294] [cc by-sa 3.0]

          可以看得出來,它不僅支持編程語言的基本語法,還支持查詢語言基礎之外的工具包的用法。

          IDE+編輯器

          前面介紹了它在命令行下的用法,其實,cht.sh更強大的是它不僅支持命令行,它還可以在常用的IDE、編輯器下用。

          例如:

          • Vim
          • Emacs
          • Sublime
          • IDEA
          • VS Code
          • IDEA
          • ...

          除此之外,它還是跨平臺的,在Windows、Linux、macOS下都可以用。

          另外,這款工具在編輯器、IDE下功能更加豐富,甚至可以自動生成代碼片段,直接補全答案。

          下面看一下效果!

          Sublime:

          IDEA:

          VS Code:

          最后再補充一點,在知識方面,它覆蓋也非常全,Python、JavaScript、Go、C++、Linux、php,我們在開發中遇到的很多問題通過cht.sh都可以快速得到答案!

          傳送門

          建議大家有空可以多瀏覽Github,有很多好用的開源免費工具。但是,目前Github上項目多如牛毛,而且刷榜現在也非常嚴重,想要找到優質的項目變得越來越難。這里,給大家推薦Github上一個非常不錯的項目《DevWeekly》,這個項目每周都會精挑細選一些優質的開源項目,涵蓋C++、JAVA、JavaScript、Python、Go等不同編程語言。此外,還有一些開源工具、優秀的技術文章:

          https://github.com/Jackpopc/DevWeekly


          主站蜘蛛池模板: 无码丰满熟妇浪潮一区二区AV| 国产亚洲综合精品一区二区三区 | 日韩一区二区三区视频久久| 国产一区中文字幕| 综合久久一区二区三区 | 亚洲av综合av一区| 亚洲美女高清一区二区三区| 亚洲欧美日韩一区二区三区在线 | 国产精品va一区二区三区| 日本精品一区二区三区在线观看| 国产熟女一区二区三区五月婷| 中文字幕精品一区二区2021年| 国产亚洲一区二区三区在线不卡 | 激情无码亚洲一区二区三区| 亚洲国产精品第一区二区| 精品成人一区二区三区四区| 视频一区视频二区在线观看| 玩弄放荡人妻一区二区三区| 亚洲色偷精品一区二区三区| 亚洲Av无码一区二区二三区| 亚洲一区精品中文字幕| 国产精品视频一区二区三区四| 综合久久一区二区三区| 精品人妻少妇一区二区三区| 国产乱码伦精品一区二区三区麻豆| 视频一区二区三区人妻系列| 一区二区三区内射美女毛片| 视频一区二区三区人妻系列| 亚洲免费视频一区二区三区| 黑人大战亚洲人精品一区| 精品国产一区二区三区免费| 无码乱人伦一区二区亚洲| 亚洲综合一区二区国产精品| 国产精品一区二区久久精品| 国产成人一区二区三区| 免费一区二区无码视频在线播放| 日韩精品一区二区三区中文字幕| 一区二区在线免费视频| 亚洲欧洲一区二区三区| 国产福利精品一区二区| 亚洲综合av一区二区三区|