Skip to content

异常与文件

数据会处理了,看失败怎么抛、文件和环境变量怎么读。

try / except / raise

python
try:
    content_text = fetch_article_text(item["link"])
except Exception as exc:
    fetch_error = str(exc)

raise RuntimeError(f"Failed: {last_error}")
js
try {
  contentText = await fetchArticleText(item.link)
} catch (exc) {
  fetchError = String(exc)
}

throw new Error(`Failed: ${lastError}`)
PythonJavaScript
except Exception as exccatch (exc)
raise ...throw ...
class E(RuntimeError): passclass E extends Error {}

with(用完自动关)

python
with httpx.Client(timeout=timeout_seconds) as client:
    resp = client.get(url)
    resp.raise_for_status()
    return resp.text
js
const resp = await fetch(url)
if (!resp.ok) throw new Error(String(resp.status))
return await resp.text()

withtry/finally 里释放资源。

Path 与读写

python
ROOT = Path(__file__).resolve().parent.parent
xml = (Path(__file__).resolve().parent / "cache" / "feed.xml").read_text(encoding="utf-8")
article_path.write_text(row.content_text, encoding="utf-8")
if article_path.exists():
    ...
js
import path from 'path'
import { fileURLToPath } from 'url'
import fs from 'fs'

const __dirname = path.dirname(fileURLToPath(import.meta.url))
const ROOT = path.resolve(__dirname, '..')
const xml = fs.readFileSync(path.join(__dirname, 'cache', 'feed.xml'), 'utf-8')
PythonJavaScript
Path(__file__).resolve().parentimport.meta.url 推出 __dirname
path / "cache" / "a.xml"path.join(dir, 'cache', 'a.xml')
.parent / .parents[1]path.dirname 一次 / 两次
.read_text(...)fs.readFileSync(..., 'utf-8')
.exists()fs.existsSync(...)

JSON 与环境变量

python
data = json.loads(payload)
body = json.dumps(data, ensure_ascii=False)
api_key = os.getenv("QWEN_API_KEY", "").strip()
js
const data = JSON.parse(payload)
const body = JSON.stringify(data)
const apiKey = (process.env.QWEN_API_KEY || '').trim()

Python 默认 dumps 会把中文收成 \uXXXX,要中文原文就加 ensure_ascii=False

计时近似:time.perf_counter()performance.now()(毫秒再换算)。

subprocess.run

起一个子进程,等它结束,拿回码和输出。

python
completed = subprocess.run(
    [sys.executable, "-c", code],
    shell=False,
    capture_output=True,
    text=True,
    encoding="utf-8",
    timeout=5,
)
return completed.returncode, completed.stdout
js
import { spawnSync } from 'child_process'

const completed = spawnSync(process.execPath, ['-e', code], {
  encoding: 'utf-8',
  timeout: 5000,
  stdio: 'pipe',
})
return [completed.status, completed.stdout]
PythonJavaScript
subprocess.run([...])spawnSync(cmd, args)
capture_output=Truestdio: 'pipe'
text=True / encoding=encoding: 'utf-8'
timeouttimeout 毫秒
completed.returncodecompleted.status

shell=False 只是不经过 Shell,不是沙箱

Path.rglob

按通配递归找文件。relative_to 去掉根前缀,as_posix() 统一成 /

python
refs = []
for path in sorted(directory.rglob("*.md")):
    if path.is_file():
        refs.append(path.relative_to(root).as_posix())
js
import { globSync } from 'node:fs'

const refs = globSync('**/*.md', { cwd: directory })
  .sort()
  .map((rel) => rel.replaceAll('\\', '/'))
PythonJavaScript
directory.rglob("*.md")globSync('**/*.md', { cwd })
path.relative_to(root)cwd 已经是相对路径
as_posix()replaceAll('\\', '/')

下一页叠:类型注解、dataclass、Pydantic。