ArgumentParser (argparse) When executing a program written in Python on the command line, you can easily use command line arguments by using ArgumentParser (argparse).

Command line arguments are something like this:

```
python test.py -t 10
```

Instantaneous type is generally

```
e=V_{m} \sin(2 \pi f t \pm \phi)
```

It is represented by. This time

```
V_{m}[V],f[Hz],\phi[deg]
```

With command line variables ([] is the unit in the program) and try to draw various graphs.

Load the library. You can use it by reading argparse.

```
import argparse
```

Define the initial value of each argument

```
parser = argparse.ArgumentParser()
parser.add_argument('--phase', '-p', type=float, default=0, help='Definition of a point in time')
parser.add_argument('--voltage', '-v', type=float, default=100, help='Definition of a effective value')
parser.add_argument('--frequency', '-f', type=float, default=60, help='Definition of a frequency')
parser.add_argument('--sampletime', '-t', type=float, default=0.0001, help='Definition of sampletime')
args = parser.parse_args()
```

Display of specified numerical value

```
print('phase : {}\n'.format(args.phase))
print('voltage : {}\n'.format(args.voltage))
print('frequency : {}\n'.format(args.frequency))
```

Drawing a graph

```
t = np.arange(0, 1/60, args.sampletime)
y1 = args.voltage * np.sqrt(2) * np.sin(2 * np.pi * args.frequency * t + np.deg2rad(args.phase))
y2 = args.voltage * np.sqrt(2) * np.sin(2 * np.pi * args.frequency * t)
plt.plot(t, y1)
plt.plot(t, y2)
plt.grid(True)
plt.show()
#plt.savefig("img.png ")
```

At the command line

```
python test.py -p 45
```

given that

To get

```
import numpy as np
import argparse
import matplotlib.pyplot as plt
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--phase', '-p', type=float, default=0, help='Definition of a point in time')
parser.add_argument('--voltage', '-v', type=float, default=100, help='Definition of a effective value')
parser.add_argument('--frequency', '-f', type=float, default=60, help='Definition of a frequency')
parser.add_argument('--sampletime', '-t', type=float, default=0.0001, help='Definition of sampletime')
args = parser.parse_args()
print('phase : {}\n'.format(args.phase))
print('voltage : {}\n'.format(args.voltage))
print('frequency : {}\n'.format(args.frequency))
t = np.arange(0, 1/60, args.sampletime)
y1 = args.voltage * np.sqrt(2) * np.sin(2 * np.pi * args.frequency * t + np.deg2rad(args.phase))
y2 = args.voltage * np.sqrt(2) * np.sin(2 * np.pi * args.frequency * t)
plt.plot(t, y1)
plt.plot(t, y2)
plt.grid(True)
plt.show()
if __name__ == '__main__':
main()
```

Recommended Posts