First file path value not added into array on linux ubuntu - python

Running a python script on linux
pngs = []
for idx, device in enumerate(udid):
pngs += glob.glob(os.getcwd() + "/logs/" + device + "_" + get_model_of_android_phone(device) + "/" + "*.png")
print(glob.glob(os.getcwd() + "/logs/" + device + "_" + get_model_of_android_phone(device) + "/" + "*.png"))
The for loop will run twice and 2 pngs will be added into the array.
However, only the 2nd one was added into the array.
Not too sure why the first one is missing from the array.
When i try to print the entire path, the entire path is showing.
Example of the file path
['/home/ubuntu/logs/123456789_SM-G920I/123456789google_search_android.png']

have you tried with append?
for idx, device in enumerate(udid):
pngs.append(glob.glob(os.getcwd() + "/logs/" + device + "_" + get_model_of_android_phone(device) + "/" + "*.png"))
print(glob.glob(os.getcwd() + "/logs/" + device + "_" + get_model_of_android_phone(device) + "/" + "*.png"))```

Related

When trying to append a string to a list I get an error

I am coding a script in python that automatically writes a file which you can use in the DecentSampler plugin, I am running into an error right now which I am not understanding.
noteGroups = []
firstGroup = True
print(noteGroups)
for file in files: #Writes all the files in the pack.
rfeS = ""
strFile = str(file)
rfe = strFile.split(".", 1)
rfe.pop(-1)
for rfeX in rfe:
rfeS += rfeX
filesSplit = rfeS.split("_", 1)
note = filesSplit[0]
rr = filesSplit[1]
noteList = note.split("delimiter")
print(noteList)
if note not in noteGroups:
noteGroups = noteGroups.append(note)
print(noteGroups)
if firstGroup:
dsp.write("\n </group>")
firstGroup = False
dsp.write("\n <group>")
dsp.write("\n <sample path=\"" + dir + "/" + file + "\" volume=\"5dB\" rootNote=\"" + note + "\" loNote=\"" + note + "\" hiNote=\"" + note + "\" seqPosition=\"" + rr + "\" />")
else:
print(noteGroups)
dsp.write("\n <sample path=\"" + dir + "/" + file + "\" volume=\"5dB\" rootNote=\"" + note + "\" loNote=\"" + note + "\" hiNote=\"" + note + "\" seqPosition=\"" + rr + "\" />")
print(noteGroups)
I am getting the error
File "D:\Python\GUI-test\dshgui.py", line 109, in dspWrite
if note not in noteGroups:
TypeError: argument of type 'NoneType' is not iterable
But if I try this:
noteGroups = ["test", "test"]
note = "A2"
noteGroups.append(note)
print(noteGroups)
It does function properly...
Does anyone know why? And how I can fix it?
The problem is this line:
noteGroups = noteGroups.append(note)
append modifies the list in-place and then it returns None. Don't assign that None value back to the name of the original list. Just do:
noteGroups.append(note)

Frozen Python File Can't access "Save_File"

After packing my program I decided to test it out to make sure it worked, a few things happened, but the main issue is with the Save_File.
I use a Save_File.py for data, static save data. However, the frozen python file can't do anything with this file. It can't write to it, or read from it. Writing says saved successful but on load it resets all values to zero again.
Is it normal for any .py file to do this?
Is it an issue in pyinstaller?
Bad freeze process?
Or is there some other reason that the frozen file can't write, read, or interact with files not already inside it? (Save_File was frozen inside and doesn't work, but removing it causes errors, similar to if it never existed).
So the exe can't see outside of itself or change within itself...
Edit: Added the most basic version of the save file, but basically, it gets deleted and rewritten a lot.
def save():
with open("Save_file.py", "a") as file:
file.write("healthy = " + str(healthy) + "\n")
file.write("infected = " + str(infected) + "\n")
file.write("zombies = " + str(zombies) + "\n")
file.write("dead = " + str(dead) + "\n")
file.write("cure = " + str(cure) + "\n")
file.write("week = " + str(week) + "\n")
file.write("infectivity = " + str(infectivity) + "\n")
file.write("infectivity_limit = " + str(infectivity_limit) + "\n")
file.write("severity = " + str(severity) + "\n")
file.write("severity_limit = " + str(severity_limit) + "\n")
file.write("lethality = " + str(lethality) + "\n")
file.write("lethality_limit = " + str(lethality_limit) + "\n")
file.write("weekly_infections = " + str(weekly_infections) + "\n")
file.write("dna_points = " + str(dna_points) + "\n")
file.write("burst = " + str(burst) + "\n")
file.write("burst_price = " + str(burst_price) + "\n")
file.write("necrosis = " + str(necrosis) + "\n")
file.write("necrosis_price = " + str(necrosis_price) + "\n")
file.write("water = " + str(water) + "\n")
file.write("water_price = " + str(water_price) + "\n")
file.write("air = " + str(air) + "\n")
file.write("blood = " + str(blood) + "\n")
file.write("saliva = " + str(saliva) + "\n")
file.write("zombify = " + str(zombify) + "\n")
file.write("rise = " + str(rise) + "\n")
file.write("limit = int(" + str(healthy) + " + " + str(infected) + " + " + str(dead) + " + " + str(zombies) + ")\n")
file.write("old = int(1)\n")
Clear.clear()
WordCore.word_corex("SAVING |", "Save completed successfully")
time.sleep(2)
Clear.clear()
player_menu()
it's probably because the frozen version of the file (somewhere in a .zip file) is loaded and never the one you're writing (works when the files aren't frozen)
That's bad practice to:
- have a zillion global variables to hold your persistent data
- generate code in a python file just to evaluate it back again (it's _self-modifying code_).
If you used C or C++ language, would you generate some code to store your data then compile it in your new executable ? would you declare 300 globals? I don't think so.
You'd be better off with json data format and a dictionary for your variables, that would work for frozen or not frozen:
your dictionary would be like:
variables = {"healthy" : True, "zombies" : 345} # and so on
Access your variables:
if variables["healthy"]: # do something
then save function:
import json
def save():
with open("data.txt", "w") as file:
json.dump(variables,file,indent=3)
creates a text file with data like this:
{
"healthy": true,
"zombies": 345
}
and load function (declaring variables as global to avoid creating the same variable, but local only)
def load():
global variables
with open("data.txt", "r") as file:
variables = json.load(file)

for loop inside a string

I'm trying to write a script in python to make my job easier.
I need to use os.system to call some functions to an external software.
Is there a way to insert a for loop inside this string, without having to write obs_dir[n] every time??
import os
obs_dir = ['18185','18186','18187','19926','19987','19994','19995','20045','20046','20081']
xid = ['src21']
i=0
os.system("pset combine_spectra src_arfs=/"
+ obs_dir[0] + "/" + xid[i] + "_" + obs_dir[0] + "_spectrum.arf,"
+ "/" + obs_dir[1] + "/" + xid[i] + "_" + obs_dir[1] + "_spectrum.arf,"
+ "/" + obs_dir[2] + "/" + xid[i] + "_" + obs_dir[2] + "_spectrum.arf,"
+ "/" + obs_dir[3] + "/" + xid[i] + "_" + obs_dir[3] + "_spectrum.arf,"
+ "/" + obs_dir[4] + "/" + xid[i] + "_" + obs_dir[4] + "_spectrum.arf,"
+ "/" + obs_dir[5] + "/" + xid[i] + "_" + obs_dir[5] + "_spectrum.arf,"
+ "/" + obs_dir[6] + "/" + xid[i] + "_" + obs_dir[6] + "_spectrum.arf,"
+ "/" + obs_dir[7] + "/" + xid[i] + "_" + obs_dir[7] + "_spectrum.arf,"
+ "/" + obs_dir[8] + "/" + xid[i] + "_" + obs_dir[8] + "_spectrum.arf,"
+ "/" + obs_dir[9] + "/" + xid[i] + "_" + obs_dir[9] + "_spectrum.arf")
You can create the required command by first iterating over the list(obs_dir) and forming the string.
Ex:
import os
obs_dir = ['18185','18186','18187','19926','19987','19994','19995','20045','20046','20081']
xid = ['src21']
s = "pset combine_spectra src_arfs="
for i in obs_dir:
s += "/{0}/{1}_{0}_spectrum.arf, ".format(i, xid[0])
s = s.strip().rstrip(',')
print s
#os.system(s)
I think this might be what you want
import os
obs_dir = ['18185','18186','18187','19926','19987','19994','19995','20045','20046','20081']
xid = ['src21']
str_cmd = "pset combine_spectra src_arfs=" + obs_dir[0]
separator = ""
for dir in obs_dir
str_cmd + = separator + "/" + dir + "/" + xid[i] + "_" + dir + "_spectrum.arf"
separator = ","
os.system(str_cmd)
You have xid[i], but no i, so using xid[0],
"/{}/{}_{}_spectrum.arf".format(obs_dir[1],xid[0],obs_dir[1])
gives
'/18186/src21_18186_spectrum.arf'
So, format helps.
Also, join will help join these into a comma separated string:
",".join(['a', 'b'])
gives
'a,b'
Joining this together you get
s = ",".join(["/{}/{}_{}_spectrum.arf".format(o,xid[0],o) for o in obs_dir])
giving the parameter(s) you want
'/18185/src21_18185_spectrum.arf,/18186/src21_18186_spectrum.arf,/18187/src21_18g187_spectrum.arf,/19926/src21_19926_spectrum.arf,/19987/src21_19987_spectrum.arfg,/19994/src21_19994_spectrum.arf,/19995/src21_19995_spectrum.arf,/20045/src21_20g045_spectrum.arf,/20046/src21_20046_spectrum.arf,/20081/src21_20081_spectrum.arfg'
without a spare ',' on the end.
Then use it
os.system("pset combine_spectra src_arfs=" + s)
Not in the string, but we can build the string using features like list comprehension (in this case, a generator expression) and string joining:
obs_dir = ['18185','18186','18187','19926','19987','19994','19995','20045','20046','20081']
xid = ['src21']
i = 0
print("pset combine_spectra src_arfs=" +
",".join("/{0}/{1}_{0}_spectrum.arf".format(n,xid[i])
for n in obs_dir))

Adding the values of two strings using Python and XML path

It generates an output with wallTime and setupwalltime into a dat file, which has the following format:
24000 4 0
81000 17 0
192000 59 0
648000 250 0
1536000 807 0
3000000 2144 0
6591000 5699 0
I would like to know how to add the two values i.e.(wallTime and setupwalltime) together. Can someone give me a hint? I tried converting to float, but it doesn’t seem to work.
import libxml2
import os.path
from numpy import *
from cfs_utils import *
np=[1,2,3,4,5,6,7,8]
n=[20,30,40,60,80,100,130]
solver=["BiCGSTABL_iluk", "BiCGSTABL_saamg", "BiCGSTABL_ssor" , "CG_iluk", "CG_saamg", "CG_ssor" ]# ,"cholmod", "ilu" ]
file_list=["eval_BiCGSTABL_iluk_default", "eval_BiCGSTABL_saamg_default" , "eval_BiCGSTABL_ssor_default" , "eval_CG_iluk_default","eval_CG_saamg_default", "eval_CG_ssor_default" ] # "simp_cholmod_solver_3D_evaluate", "simp_ilu_solver_3D_evaluate" ]
for cnt_np in np:
i=0
for sol in solver:
#open write_file= "Graphs/" + "Np"+ cnt_np + "/CG_iluk.dat"
#"Graphs/Np1/CG_iluk.dat"
write_file = open("Graphs/"+ "Np"+ str(cnt_np) + "/" + sol + ".dat", "w")
print("Reading " + "Graphs/"+ "Np"+ str(cnt_np) + "/" + sol + ".dat"+ "\n")
#loop through different unknowns
for cnt_n in n:
#open file "cfs_calculations_" + cnt_n +"np"+ cnt_np+ "/" + file_list(i) + "_default.info.xml"
read_file = "cfs_calculations_" +str(cnt_n) +"np"+ str(cnt_np) + "/" + file_list[i] + ".info.xml"
print("File list" + file_list[i] + "vlaue of i " + str(i) + "\n")
print("Reading " + " cfs_calculations_" +str(cnt_n) +"np"+ str(cnt_np) + "/" + file_list[i] + ".info.xml" )
#read wall and cpu time and write
if os.path.exists(read_file):
doc = libxml2.parseFile(read_file)
xml = doc.xpathNewContext()
walltime = xpath(xml, "//cfsInfo/sequenceStep/OLAS/mechanic/solver/summary/solve/timer/#wall")
setupwalltime = xpath(xml, "//cfsInfo/sequenceStep/OLAS/mechanic/solver/summary/setup/timer/#wall")
# cputime = xpath(xml, "//cfsInfo/sequenceStep/OLAS/mechanic/solver/summary/solve/timer/#cpu")
# setupcputime = xpath(xml, "//cfsInfo/sequenceStep/OLAS/mechanic/solver/summary/solve/timer/#cpu")
unknowns = 3*cnt_n*cnt_n*cnt_n
write_file.write(str(unknowns) + "\t" + walltime + "\t" + setupwalltime + "\n")
print("Writing_point" + str(unknowns) + "%f" ,float(setupwalltime ) )
doc.freeDoc()
xml.xpathFreeContext()
write_file.close()
i=i+1
In java you can add strings and floats. What I understand is that you need to add the values and then display them. That would work (stringing the sum)
write_file.write(str(unknowns) + "\f" + str(float(walltime) + float(setupwalltime)) + "\n")
You are trying to add a str to a float. That doesn't work. If you want to use string concatenation, first coerce all of the values to str. Try this:
write_file.write(str(unknowns) + "\t" + str(float(walltime) + float(setupwalltime)) + "\n")
Or, perhaps more readably:
totalwalltime = float(walltime) + float(setupwalltime)
write_file.write("{}\t{}\n".format(unknowns, totalwalltime))

How to encrypt a .bin file

I need to encrypt 3 .bin files which contain 2 keys for Diffie-Hellman. I have no clue how to do that, all I could think of was what I did in the following Python file. I have an example what the output should look like but my code doesn't seem to produce the right keys. The output file server.ini is used by a client to connect to a server.
import base64
fileList = [['game_key.bin', 'Game'], ['gate_key.bin', 'Gate'], ['auth_key.bin', 'Auth']]
iniList = []
for i in fileList:
file = open(i[0], 'rb')
n = list(file.read(64))
x = list(file.read(64))
file.close()
n.reverse()
x.reverse()
iniList.append(['Server.' + i[1] + '.N "' + base64.b64encode("".join(n)) + '"\n', 'Server.' + i[1] + '.X "' + base64.b64encode("".join(x)) + '"\n'])
iniList[0].append('\n')
#time for user Input
ip = '"' + raw_input('Hostname: ') + '"'
dispName = 'Server.DispName ' + '"' + raw_input('DispName: ') + '"' + '\n'
statusUrl = 'Server.Status ' + '"' + raw_input('Status URL: ') + '"' + '\n'
signupUrl = 'Server.Signup ' + '"' + raw_input('Signup URL: ') + '"' + '\n'
for l in range(1, 3):
iniList[l].append('Server.' + fileList[l][1] + '.Host ' + ip + '\n\n')
for l in [[dispName], [statusUrl], [signupUrl]]:
iniList.append(l)
outFile = open('server.ini', 'w')
for l in iniList:
for i in l:
outFile.write(i)
outFile.close()
The following was in my example file:
# Keys are Base64-encoded 512 bit RC4 keys, as generated by DirtSand's keygen
# command. Note that they MUST be quoted in the commands below, or the client
# won't parse them correctly!
I also tried it without inverting n and x

Categories