家好,我是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或者模版引擎還是有區別的。
官方給了一個例子,可以幫助我們觀的感受這個開發框架的能力,不妨跟著DD看看,它能做啥吧!
第一個案例,hello world
代碼很簡單,就下面這幾行。你只需要創建一個html文件,然后復制進去就可以了。
|
保存好之后,在瀏覽器里打開就能看到這樣的頁面了:
回頭再看看這個html里的內容,三個核心內容:
如果你懶得自己敲代碼的話,本文的兩個案例代碼我打包放在公眾號了,需要的朋友可以關注公眾號“程序猿DD”,回復:pyscript 獲取。
第二個案例,數據定義 + 數據展示
先創建一個data.py文件,然后加入前面的代碼。功能很簡單,就是隨機生成(x,y)的坐標
|
再創建一個html文件,加入下面的代碼
|
這里就稍微復雜一些了,除了hello world中的幾個要點外,這里還有這幾個要關注的地方:
這個頁面的執行效果是這樣的:
是不是很神奇呢?整個過程中都沒有大家熟悉的cs、js內容,就完成了這樣一個圖的頁面實現。
最后,談談在整個嘗試過程中,給我的幾個感受:
這個開發框架目前還只是alpha版本,未來一定還會有更多特性與優化出來,總體上我覺得這個框架還是非常cool的,尤其對于剛學會Python,或者只會Python,但又想快速開發Web應用的小伙伴來說,可能將會是個不錯的選擇,那你覺得這個框架如何?未來會不會火?留言區聊聊吧!
數字的游戲
根據官方教程,照寫一個程序,來體驗一下rust的程序開發過程。
游戲很簡單, 就是一次次輸入比對預先生成的隨機數。
Cargo是rust的包管理工具, 對于本需求需要rand的方法, 但是該方法再rust中并不存在, 所以通過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可以下載第三方庫。
同時cargo 也可以用來建立自己的rust項目, 包括可行性程序以及庫。
可以通過
cargo new project_name -bin 創建一個rust程序
cargo new project_name --lib 創建一個庫
再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 build或cargo 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命令包含下面幾個信息:
通過這樣,它就可以快速在終端下給出問題的答案。
如果你不想要文字描述,只想要「純凈」的答案,還可以通過參數來處理:
$ 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()
# 
#
# [gcalmettes] [so/q/12864294] [cc by-sa 3.0]
可以看得出來,它不僅支持編程語言的基本語法,還支持查詢語言基礎之外的工具包的用法。
前面介紹了它在命令行下的用法,其實,cht.sh更強大的是它不僅支持命令行,它還可以在常用的IDE、編輯器下用。
例如:
除此之外,它還是跨平臺的,在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
*請認真填寫需求信息,我們會在24小時內與您取得聯系。