repeating program (python) - loops

Heyho
I want to repeat a program after runnning a task. At the start of the program I ask some questions, than the code jumps into the task. If the task is done the questions sholud ask again..
Each Question reads some infos at the serial port. If i get the infos ten times ich will restart the programm.. but the window closes and i must start the file..
What can i do?
import serial
import struct
import datetime
print("\n")
print("This tool reads the internal Bus ")
print("-----------------------------------------------------------------------")
COM=input("Check your COM Port an fill in with single semicolon (like: 'COM13' ): ")
ser = serial.Serial(
port=COM,
baudrate=19200,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS
)
print("\n")
print("Please choose an option: ")
print("Polling of measured values and the operating status (1)")
print("Reading Parameter memory (2)")
print("Reading Fault memory (3)")
print("EXIT (4)")
print("\n")
i=input("Reading: ")
while(i==1):
count=0
while (count<10):
print(file.name)
print(ser.isOpen())
print ("connected to: "+ ser.portstr)
data = "\xE1\x14\x75\x81"
ser.write(data)
a=(map(hex,map(ord,ser.read(46))))
with open("RS485_Reflex.txt",mode='a+') as file:
file.write(str(datetime.datetime.now()))
file.write(", Values: ,")
file.write(str(a))
file.write("\n")
print(a)
count=count+1
else:
i=0
loop=1
#-----------------------------------------------------------------------
while(i==2):
count=0
while (count<10):
print(file.name)
print(ser.isOpen())
print ("connected to: "+ ser.portstr)
data = "\xE1\x13\x00\x00\x74\x81"
ser.write(data)
a=(map(hex,map(ord,ser.read(11))))
with open("RS485_Reflex.txt",mode='a+') as file:
file.write(str(datetime.datetime.now()))
file.write(", Parameters: , ")
file.write(str(a))
file.write("\n")
print(a)
count=count+1
else:
i=0
#---------------------------------------------------------------------
while(i==3):
count=0
while (count<10):
print(file.name)
print(ser.isOpen())
print ("connected to: "+ ser.portstr)
data = "\xE1\x12\x00\x00\x73\x81"
ser.write(data)
a=(map(hex,map(ord,ser.read(11))))
with open("RS485_Reflex.txt",mode='a+') as file:
file.write(str(datetime.datetime.now()))
file.write(", Fault: , ")
file.write(str(a))
file.write("\n")
print(a)
count=count+1
else:
i=0
#----------------------------------------------------------------------
while(i==4):
file.close()
ser.close()
sys.exit(0)
file.close()
ser.close()

First, you should use If/Elif/Else statements instead of while loops.
while(i==1):
should be
if(i==1)0:
This is a simple program I wrote that you can follow:
# setup a simple run_Task method (prints number of times through the loop already)
def run_task(count):
print "Ran a certain 'task'", count,"times"
# count is a variable that will count the number of times we pass through a loop
count = 0
# loop through 10 times
while(count<10):
# ask questions
q1 = raw_input("What is your name?")
q2 = raw_input("What is your favorite color?")
# run a 'task'
run_task(count)

Related

I am not able to get any values to store in the array #AA

It is getting the correct inputs and printing them inside the for loop but when I try to send it to a function module later or if I try to print it outside the for loop it is empty.
What do I need to change?
#!/usr/bin/perl
use lib "."; # This pragma include the current working directory
use Mytools;
$inputfilename = shift #ARGV;
open (INFILE, $inputfilename) or die
("Error reading file $inputfilename: $! \n");
# Storing every line of the input file in array #file_array
while (<INFILE>){
$file_array[ $#file_array + 1 ] = $_;
}
my $protein;
my #AA;
foreach $protein (#file_array)
{
#AA = Mytools::dnaToAA($protein);
print "The main AA\n",#AA;
}
print "The main array",#file_array;
my $header1 = "AA";
my $header2 = "DNA";
Mytools::printreport($header1, $header2, \#AA, \#file_array);
You're overwriting the #AA in every iteration of the foreach loop.
Instead of
#AA = Mytools::dnaToAA($protein);
use
push #AA, Mytools::dnaToAA($protein);
See push.
Next time, try to post runnable code (see mre), i.e. avoid Mytools as they're irrelevant to the problem and make the code impossible to run for anyone else but you.

Having Trouble printing out .txt in ruby, ruby file handling

the problem is it cannot print all the text of the from a .txt file. I am able to print the first 3 lines of the txt file but not the rest. So far, I am getting an error which is in print_album': undefined local variable or methodtracks' for main:Object (NameError).
Here's the code:
*I know using global variable is no good in Ruby but this exercise ask me to do it.
module Genre
POP, CLASSIC, JAZZ, ROCK = *1..4
end
$genre_names = ['Null', 'Pop', 'Classic', 'Jazz', 'Rock']
class Album
# NB: you will need to add tracks to the following and the initialize()
attr_accessor :title, :artist, :genre, :tracks
# complete the missing code:
def initialize (atitle, aartist, agenre, arrtrk)
# insert lines here
#genre = agenre
#tracks = arrtrk
#title = atitle
#artist = aartist
end
end
class Track
attr_accessor :ttitle, :tlocation
def initialize (tname, tloc)
#ttitle = tname
#tlocation = tloc
end
end
# Reads in and returns a single track from the given file
def read_track music_file
mytrk_name = music_file.gets
mytrk_location = music_file.gets
mytrk = Track.new(mytrk_name, mytrk_location)
mytrk
end
# Returns an array of tracks read from the given file
def read_tracks music_file
count = music_file.gets().to_i
tracks = Array.new
$i = 0
# Put a loop here which increments an index to read the tracks
while $i < count do
track = read_track(music_file)
tracks << track
$i += 1
end
tracks
end
# Takes an array of tracks and prints them to the terminal
def print_tracks tracks
# print all the tracks use: tracks[x] to access each track.
$i = 0
while $i < tracks.length do
print_track(tracks[$i])
$i +=1
end
tracks
end
# Reads in and returns a single album from the given file, with all its tracks
def read_album music_file
# read in all the Album's fields/attributes including all the tracks
# complete the missing code
album_title = music_file.gets
album_artist = music_file.gets
album_genre = music_file.gets.to_i
tracks = read_tracks(music_file)
album = Album.new(album_title, album_artist, album_genre, tracks)
album
end
# Takes a single album and prints it to the terminal along with all its tracks
def print_album album
# print out all the albums fields/attributes
# Complete the missing code.
puts 'Album title is '+ album.title
puts 'Artist is ' + album.artist
puts 'Genre is ' + album.genre.to_s
puts $genre_names[album.genre]
# print out the tracks
print_tracks(tracks)
end
# Takes a single track and prints it to the terminal
def print_track track
puts('Track title is: ' + track.ttitle)
puts('Track file location is: ' + track.tlocation)
end
# Reads in an album from a file and then print the album to the terminal
def main
music_file = File.new("album.txt", "r")
album = read_album(music_file)
music_file.close()
print_album(album)
end
main
Here's is the album.txt
Greatest Hits
Neil Diamond
1
3
Crackling Rose
sounds/01-Cracklin-rose.wav
Soolaimon
sounds/06-Soolaimon.wav
Sweet Caroline
sounds/20-Sweet_Caroline.wav
Currently my output is :
Album title is Greatest Hits
Artist is Neil Diamond
Genre is 1
Pop
Expected output is :
Album title is Greatest Hits
Artist is Neil Diamond
Genre is 1
Pop
Track title is: Crackling Rose
Track file location is: sounds/01-Cracklin-rose.wav
Track title is: Soolaimon
Track file location is: sounds/06-Soolaimon.wav
Track title is: Sweet Caroline
Track file location is: sounds/20-Sweet_Caroline.wav
The problem is inside your def print_album album method. On the last line of the method it uses print_tracks(tracks), but tracks variable is undefined (that's exactly what error tells you).
You need to call print_tracks(album.tracks)

accessing array content whithin for loop - Auto Hot Key AHK

I am trying to extract the content of an array member at index i into a variable and then append it to a file.
How do I do that ?
Here is what I tried but it will not take the content of cgi[i]
firstrun(){
GuiControlGet, cgiDelay,,_cgiDelay
returnCode:=[]
for i in cgi {
msg := "http://" ip "/Nexus.cgi?session=" session "&action=" firstRunCgi[i] "&tokenoverride=1"
sendToHttp(msg)
getRespond()
returnCode[i]:=parseReturnCode()
if (returnCode[i] !=0){
addTextToGui("Setting 1st run Fail #: " i "`terrorCode: " returnCode[i] "`t"firstRunCgi[i])
txt = `ncgi[i],skipped
FileAppend, %txt%, cgiLog.txt
cgi[i] :=""
}
else{
; addTextToGui("Setting 1st run OK #: " i "`terrorCode: " returnCode[i] "`t"firstRunCgi[i])
}
Sleep (cgiDelay)
}
}
now sure why and how but this fixed it:
txt := "`n" cgi[i] ",skipped"
FileAppend, %txt%, cgiLog.csv
See here: AutoHotKey: How to access array with counter variable
In your Example you posted: For i in cgi the variable i contains your Key/Index, so you can access a Value in cgi Array with the Key/Index by: value := cgi[i]
Alternatatively you can declare two variables to hold both your Key/Index and Value directly in your For loop like so:
cgi := ["Hello", "World"]
For i, v in cgi ; Notice the comma
MsgBox % "This is the Key/Index: " i
. "`nThis is the Value from the For loop: " v
. "`nThis Value was accessed using Key/Index: " cgi[i]

Extracting values from text file using autohotkey

I have a small text file that I would like to extract some values using autohotkey.
Example of text file's content:
Date: 2014-12-02 12:06:47
Study: G585.010.411
Image: 6.24
Tlbar: 2.60
Notes: 0.74
My current code:
FileReadLine, datetime, C:\File.txt, 1
datedsp := SubStr(datetime, 7)
Sleep 500
FileReadLine, study, C:\File.txt, 2
studydsp := SubStr(study, 7)
Sleep 500
FileReadLine, image, C:\File.txt, 3
imgdsp := SubStr(image, 7)
Sleep 500
FileReadLine, notes, C:\File.txt, 5
notesdsp := SubStr(notes, 7)
Sleep 500
MsgBox %datedsp%
MsgBox %studydsp%
MsgBox %imgdsp%
MsgBox %notesdsp%
All I want to do is to grab the value of each of those lines and assign it to variables. For example, studydsp value would be G58500411, imagedsp value would be 6.24, datedsp value would be 2014-12-02 12:06:47.
Is there anyway to achieve this in a better way?
Possible issues with this code:
I am unable to get the string from the date line perhaps due to a space at
the beginning(?)
I can't get the SubStr value of either date (refer to 1st issue) or
study (perhaps because of special characters?)
You can use FileRead and RegExMatch
var:="
(
Date: 2014-12-02 12:06:47
Study: G585.010.411
Image: 6.24
Tlbar: 2.60
Notes: 0.74
)"
;~ FileRead, var, C:\file.txt
pos:=1
while pos := RegExMatch(var, "\s?(.*?):(.*?)(\v|\z)", m, pos+StrLen(m))
%m1% := m2
msgbox % "Date holds " date
. "`nStudy holds " Study
. "`nImage holds " Image
. "`nTlbar holds " Tlbar
. "`nNotes holds " Notes
Just remove the var part and uncomment the fileread line, at least thats one way to do it to :)
hope it helps
Basically the same as #blackholyman's answer, but using an object based approach by building a value map:
fileCont =
(
Date: 2014-12-02 12:06:47
Study: G585.010.411
Image: 6.24
Tlbar: 2.60
Notes: 0.74
)
valueMap := {}
; Alternatively, use: Loop, Read, C:\file.txt
Loop, Parse, fileCont, `r`n
{
RegExMatch(A_LoopField, "(.*?):(.*)", parts)
; Optionally make keys always lower case:
; StringLower, parts1, parts1
valueMap[Trim(parts1)] := Trim(parts2)
}
msgbox % "Date = " valueMap["Date"]
. "`nImage = " valueMap["Image"]
; We can also iterate over the map
out := ""
for key, val in valueMap
{
out .= key "`t= " val "`n"
}
msgbox % out

Making a reversed file without complications

I was attempting to take a file, reverse it, and save it to another file. However, I've come across a problem.
If I reverse this, for example:
The woods are lovely, dark and deep.
But I have promises to keep,
And miles to go before I sleep,
And miles to go before I sleep.
I should end up with this:
And miles to go before I sleep.
And miles to go before I sleep,
But I have promises to keep,
The woods are lovely, dark and deep.
However, what I end up getting is this:
And miles to go before I sleep.And miles to go before I sleep,
But I have promises to keep,
The woods are lovely, dark and deep.
This is my code, at the moment:
import os.path
endofprogram = False
try:
fileName = input("Enter the name of the input file: ")
print("\n")
infile = open(fileName, 'r')
outfileName = input("Enter the name of the output file: ")
print("\n")
while os.path.isfile(outfileName):
outfileName = input("File Exists. Enter name again: ")
print("\n")
outfile = open(outfileName, 'w')
except IOError:
print("Error opening file - End of program")
endofprogram = True
if endofprogram == False:
lines = infile.readlines()
for reverse in lines[::-1]:
print(reverse)
outfile.write(reverse)
outfile.close()
infile.close()
Why is this happening and how can I fix it? Thank you.
It looks like the last line of your input file doesn't end in a newline. There's a number of ways to deal with that; here's one:
for reverse in lines[::-1]:
if reverse[-1] != "\n":
reverse += "\n"
#etc

Resources