简体   繁体   中英

Automating already existing python program

So I have a program that takes the .txt data (set of integer numbers), makes a sum every n numbers (divisions), and puts that result in a new list. And then it makes a bar chart of that list.

And so far it works just fine. The only problem is that I'd like it to make the program does all this without me having to manually input the number of divisions I'd like it to make :\\

I'd like it to go through lets say a loop, that will put division to 10, 11, 12... to any number I like, and then put it all in a list, and I'd end up with multiple lists, that I can then transfer to excell, origin, or any other program, and do my analysis there.

I'll put the program, without the plotting part, and some extra things I've already asked about this:

# -*- coding: cp1250 -*-
from __future__ import division
from numpy import *
from matplotlib import rc
from matplotlib.pyplot import *
import numpy as np
import matplotlib.pyplot as plt


data = loadtxt("mion-090513-1.txt", int)

nuz = len(data)
nsmp = 10
duz = int(nuz/nsmp)

L = []

ukupni_broj=sum(data)

#Summed values calculation#
for i1 in range(0,nsmp):
    suma = 0
    for i2 in range(0,duz):
        suma += data[i1*duz+i2]
    L.append(suma)

print L

print 'Bin number is', len(L)

print 'Total event number is', ukupni_broj

So I'd basically like to have nsmp in a for loop, from some values to some values (for instance from 10-15, 20-50 in a 25 interval step, and so on).

Is that thing doable?

Also is there an easy way of exporting results in python? I searched all over but found nothing easy like loadtxt .

Here's the .txt file: https://dl.dropboxusercontent.com/u/55620972/mion-090513-1.txt

To make your program easy to automate and to be reusable, you can make a couple of things.

Separate your core functionality (eg, computations) from execution. You can put the computation into a separate module and execute it form the "main" script:

# my_processing.py
def process_file(filename, divisions):
   ...

# process_all.py:
import my_processing
filename = "..."
divisions = [10, 20, 100]
my_processing.process_file(filename, divisions)

This way you can reuse my_processing.py . Also, it is a very good habit to include main clause

def main():
    ....

if __name__ == "__main__"
    main()

If you are designing a tool, you should also define command line arguments - argparse is perfect for that. Then you can easily use it from shell scripts.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM