#!/usr/bin/python3.1 import os import sys import http.client version = “1.22.0” def…
- User
#!/usr/bin/python3.1
import os import sys import http.client
version = “1.22.0”
def main(argv): c_begin = [158200, 81900] c_end = [158801, 82501]
total = (c_end[0]-c_begin[0])*(c_end[1]-c_begin[1]) print (total) c = 0 for x in range(c_begin[0], c_end[0]): for y in range(c_begin[1], c_end[1]): c += 1 result = GetTile(x, y) flag = " " if result == 1 else “+” if flag == “+”: print(“GET {: >10} {: >10} | {:.2f}% {: ^1}”.format(x, y, round((c/total)*100,2), flag)) return 0
def GetTile(x, y):
filename = “./map/{x}_{y}_18.jpg”.format(x = x, y = y) if os.path.isfile(filename): return 1 url = “/tiles?l=sat&v={ver}&x={x}&y={y}&z=18&g=Gagarin”.format(x = x, y = y, ver = version) conn = http.client.HTTPConnection(“sat02.maps.yandex.ru”) conn.request(“GET”, url) response = conn.getresponse() if response.status == 200: data = response.read() f = open(filename, “wb”) f.write(data) f.close()
return 0
if name == “main”: sys.exit(main(sys.argv))
Перепеши этот код для rust
- Assistant
Here's a Rust version of your Python script, which fetches tiles from a specific server, checking if they exist locally and downloading them if not. Keep in mind that there are some differences in error handling and syntax between Python and Rust.
This Rust program uses the
reqwestcrate for HTTP requests and thestd::fsmodule for file operations. Make sure to addreqwestin yourCargo.tomlfile:[dependencies] reqwest = { version = "0.11", features = ["blocking", "json"] }Now, here's how you can rewrite your Python code into Rust:
use reqwest::blocking::Client; use std::fs; use std::io::Write; const VERSION: &str = "1.22.0"; fn main() { let c_begin = [158200, 81900]; let c_end = [158801, 82501]; let total = (c_end[0] - c_begin[0]) * (c_end[1] - c_begin[1]); println!("{}", total); let mut c = 0; let client = Client::new(); for x in c_begin[0]..c_end[0] { for y in c_begin[1]..c_end[1] { c += 1; let result = get_tile(&client, x, y); let flag = if result == 1 { " " } else { "+" }; if flag == "+" { println!( "GET {:>10} {:>10} | {:.2}% {:^1}", x, y, (c as f64 / total as f64) * 100.0, flag ); } } } } fn get_tile(client: &Client, x: i32, y: i32) -> i32 { let filename = format!("./map/{}_{}_18.jpg", x, y); if fs::metadata(&filename).is_ok() { return 1; } let url = format!( "/tiles?l=sat&v={}&x={}&y={}&z=18&g=Gagarin", VERSION, x, y ); let response = client.get(&format!("http://sat02.maps.yandex.ru{}", url)) .send(); match response { Ok(res) if res.status().is_success() => { if let Ok(data) = res.bytes() { let mut file = fs::File::create(&filename).expect("Unable to create file"); file.write_all(&data).expect("Unable to write data to file"); return 0; } } Err(e) => { eprintln!("Error fetching tile: {}", e); } _ => { eprintln!("Failed to retrieve tile for coordinates ({}, {})", x, y); } } return -1; // Indicate that the tile was not successfully retrieved. }Key Changes and Considerations:
- Library for HTTP Requests: Rust does not have built-in libraries for HTTP requests like Python; hence, we use the
reqwestcrate. - Error Handling: Rust emphasizes safety, and thus, error handling is more explicit. Instead of just returning an error code, we check for
OkandErrvariants. - Variable Naming: By convention, Rust uses
snake_casefor variable names. - Formatting Strings: Rust uses the
format!macro similarly to Python'sstr.format. - File Handling: Rust requires explicit closure of file handles or using the
write_allmethod.
Before running this code, ensure you have a proper Rust environment set up and the necessary dependencies installed.
- Library for HTTP Requests: Rust does not have built-in libraries for HTTP requests like Python; hence, we use the