make_csv/
lib.rs

1/// Creates a csv writer to the given file path.
2///
3/// ## Usage:
4/// ```no_run
5/// use make_csv::{csv_start, csv_entry};
6///
7/// let mut wtr = csv_start!("out.csv");
8/// ```
9#[macro_export]
10macro_rules! csv_start {
11    ($filename: expr) => {
12        csv::Writer::from_path($filename).unwrap()
13    };
14}
15
16/// Adds a row to the given csv writer.
17///
18/// ## Syntax:
19/// `csv_entry!(writer <- one, two, three)`
20/// Here, `one` etc are expressions that can be formatted to String.
21///
22/// ## Usage:
23/// ```no_run
24/// use make_csv::{csv_start, csv_entry, csv_stop};
25///
26/// let mut wtr = csv_start!("out.csv");
27/// csv_entry!(wtr <- "header_0", "header_1");
28/// csv_entry!(wtr <- 0.0, 1.0);
29/// csv_stop!(wtr);
30/// ```
31/// This will result in the following `.csv` file:
32/// ```csv
33/// header_0,header_1
34/// 0.0,1.0
35/// ```
36#[macro_export]
37macro_rules! csv_entry {
38    ($writer: ident <- $($header:expr),*) => {
39        $writer.write_record(&[$(format!("{}", $header).as_str()),*]).expect("ow");
40    };
41}
42
43/// Flushes the writer and writes to file.
44///
45/// ## Usage:
46/// ```no_run
47/// use make_csv::{csv_start, csv_entry, csv_stop};
48///
49/// let mut wtr = csv_start!("out.csv");
50/// csv_entry!(wtr <- "header_0", "header_1");
51/// csv_entry!(wtr <- 0.0, 1.0);
52/// csv_stop!(wtr);
53/// ```
54///
55#[macro_export]
56macro_rules! csv_stop {
57    ($writer: ident) => {
58        $writer.flush().unwrap();
59        drop($writer);
60    };
61}
62
63/// Runs a python file and blocks until it completes.
64///
65/// Useful for plotting using a file `plot.py` which
66/// reads some `.csv` file and plots the data.
67///
68/// ## Arguments
69/// - `arg0, arg1, arg2, ...`: comma separated arguments to be
70///     passed to python3 (python filename for example)
71///
72/// ## Requirements
73/// `python3` needs to be in PATH.
74///
75/// ## Usage
76/// ```no_run
77/// make_csv::python!("plot.py", "data.csv");
78/// ```
79#[macro_export]
80macro_rules! python {
81    ($($arg: expr),*) => {
82        std::process::Command::new("python3")
83            $(.arg($arg))*
84            .output()
85            .unwrap();
86    };
87}