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 docoptdocoptreads 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.
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.
