Build a Python CLI to Fetch 12306 Train Tickets in Seconds
This tutorial walks you through creating a Python command‑line tool named “tickets” that, using virtualenv, docopt, and prettytable, retrieves real‑time train ticket information from China’s 12306 service by specifying departure, destination, and date, and displays the results in a formatted table.
Everyone has used the 12306 website; this guide shows how to write a Python program that returns train ticket information from the command line.
1. Interface Design
The small application is called tickets . Users only need to provide a departure station, a destination station, and a date. Example usage: $ tickets from to date With optional flags, e.g.:
$ tickets -gdtkz from to date2. Development Environment
Create an isolated Python 3 environment with virtualenv and activate it:
$ virtualenv -p /usr/bin/python3 venv $ . venv/bin/activate3. Argument Parsing
Use the docopt library for simple command‑line parsing. Install it first:
$ pip3 install docopt docoptreads the usage pattern defined in the script’s docstring and extracts the arguments automatically.
4. Fetching Data
Query the 12306 API with a URL such as:
https://kyfw.12306.cn/otn/lcxxcx/query?purpose_codes=ADULT&queryDate=2016-07-01&from_station=SHH&to_station=BJPStation codes are obtained from the JavaScript file station_name.js and saved locally as stations.html for lookup.
5. Displaying Results
Install prettytable to format the output like a MySQL table: $ pip3 install prettytable The final output shows the train schedule in a neatly aligned table.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
