Am trying to read a population_data.json file but when ever i run the code it doesn't display any data in the file and i don't get any Error too? - python-3.7

import json
#Load the data into a list.
filename = 'population_data.json'
with open(filename)as f:`enter code here`
pop_data = json.load(f)
enter code here
#Print the 2010 population data for each country.
for pop_dict in pop_data:`enter code here`
if pop_dict['Year'] == '2010':
country_name = pop_dict['Country Name']
population = int(float(pop_dict['Value']))
print(country_name + " : " + str(population))
Am trying to extract data from a population_data.json file, but whenever i run my code it doesn't show any result and i don't get any Errors, i have save the population data file in the same folder with the code but i still have that same problem, i don't get any result of the data in the shell. i would be glad if someone can help.Thank you .
enter code here
import json
#Load the data into a list.
filename = 'population_data.json'
with open(filename)as f:`enter code here`
pop_data = json.load(f)
enter code here
#Print the 2010 population data for each country.
for pop_dict in pop_data:`enter code here`
if pop_dict['Year'] == '2010':
country_name = pop_dict['Country Name']
population = int(float(pop_dict['Value']))
print(country_name + " : " + str(population))

I would suggest starting your script in the python debugger (pdb). You can start it either by starting your script like this:
python3 -m pdb your_script.py
or by importing the pdb module. Adding the following line into your python file (for example after import json, or any other):
import pdb; pdb.set_trace()
Once it is loaded, the debugger stops at the first instruction and shows the debugger promt (Pdb) . Continue execution line by line by typing next and hitting ENTER until you hit a line where something interesting is happening. The debugger prints always the next instruction and the script path and line.
Debugger output is added below, everything after (Pdb) you have to type and confirm with ENTER
(Pdb) next
> /path/to/your_script.py(7)<module>()
-> pop_data = json.load(f)
(Pdb) next
> /path/to/your_script.py(11)<module>()
-> for pop_dict in pop_data:
Now let the debugger print contents of a variable
(Pdb) p pop_data
{"Probably": "something", "you": "don't expect here"}
I suspect either the for loop yields 0 pop_dicts and therefore the loop body is never executed, or no pop_dict key Year has value 2010 and the if body is never executed.
Alternative to type next often (== single stepping): set a break point on a specific line (your_script.py:11), and continue execution until the breakpoint is hit
(Pdb) break your_script.py:11
Breakpoint 1 at /path/to/your_script.py:11
(Pdb) continue
> /path/to/your_script.py(11)<module>()
-> for pop_dict in pop_data:
(Pdb)
For additional debugger commands see pdb commands

Related

Replacement of text in xml file by AHK - get error when trying to open as xml file

I am using an AHK script to replace some text in an .xml file (Result.xml in this case). The script then saves a file as Result_copy.xml. It changes exactly what I need, but when I try to open the new xml file, it won't open, giving me the error:
This page contains the following errors:
error on line 4 at column 16: Encoding error
Below is a rendering of the page up to the first error.
I only replaced text at line 38 using:
#Include TF.ahk
path = %1%
text = %2%
TF_ReplaceLine(path, 38, 38, text)
%1% and %2% are given by another program and are working as should
I also see that the orginal Result.xml is 123 kb and Result_copy.xml is 62 kb, even though I only add text. When I take Result.xml and manually add the text and save it, it's 123 kb and still opens. so now both files contain exactly the same Characters, but one won't open as xml. I think that something happens during saving/copying, which I don't understand.
Could someone help me out on this one? I don't have a lot of experience in AHK scripting and do not have a programming background.
Thank you in advance!
Michel
TF.ahk contains this:
/*
Name : TF: Textfile & String Library for AutoHotkey
Version : 3.8
Documentation : https://github.com/hi5/TF
AutoHotkey.com: https://www.autohotkey.com/boards/viewtopic.php?f=6&t=576
AutoHotkey.com: http://www.autohotkey.com/forum/topic46195.html (Also for examples)
License : see license.txt (GPL 2.0)
Credits & History: See documentation at GH above.
TF_ReplaceLine(Text, StartLine = 1, Endline = 0, ReplaceText = "")
{
TF_GetData(OW, Text, FileName)
TF_MatchList:=_MakeMatchList(Text, StartLine, EndLine, 0, A_ThisFunc) ; create MatchList
Loop, Parse, Text, `n, `r
{
If A_Index in %TF_MatchList%
Output .= ReplaceText "`n"
Else
Output .= A_LoopField "`n"
}
Return TF_ReturnOutPut(OW, OutPut, FileName)
}

How to catch OS-COMMAND results in Progress-4GL?

I'm using the logging facilities, as described in this other post:
OUTPUT TO VALUE("C:\Temp_Folder\logfile.txt").
...
PUT UNFORMATTED "Start : Check-zones" SKIP.
...
OUTPUT CLOSE.
This is working fine.
Now I would like to add the results of an OS-COMMAND in the output file.
I've already tried the following: (putting the results in a newly to be created file)
OS-COMMAND NO-WAIT VALUE("WMIC printer get name, deviceID >> C:\Temp_Folder\Printers.txt").
This is working fine.
So, I know the command is working fine. However, the following is not working:
OS-COMMAND NO-WAIT VALUE("WMIC printer get name, deviceID >> C:\Temp_Folder\LogFile.txt").
This is obvious, because C:\Temp_Folder\Logfile.txt is locked for writing by the progress application, so the shell, opened by OS-COMMAND can't write to that file.
In order to overcome this, I would like to catch the results of the OS-COMMAND's results.
How can I do this?
Unfortunately back in the dark ages when os-command was designed, it was considered useful to suppress all errors.
You can either start a batch file and let that do some “guaranteed” output error handling, see https://knowledgebase.progress.com/articles/Article/21039
Or (since you are on Windows) you can use the .Net system diagnostics process class (which you will want to wrap in your own method or function to simplify use):
DEFINE VARIABLE oProcess AS System.Diagnostics.Process NO-UNDO.
DEFINE VARIABLE lcstderr AS LONGCHAR NO-UNDO.
DEFINE VARIABLE lcstdout AS LONGCHAR NO-UNDO.
oProcess = NEW System.Diagnostics.Process().
oProcess:StartInfo:FileName = "wmic.exe".
oProcess:StartInfo:Arguments = "printer get name, deviceID".
oProcess:StartInfo:CreateNoWindow = TRUE.
oProcess:StartInfo:UseShellExecute = FALSE.
oProcess:StartInfo:RedirectStandardError = TRUE.
oProcess:StartInfo:RedirectStandardOutput = TRUE.
oProcess:Start().
lcstdout = oProcess:StandardOutput:ReadToEnd().
lcstderr = oProcess:StandardError:ReadToEnd().
oProcess:WaitForExit().
lcstdout = lcstdout + oProcess:StandardOutput:ReadToEnd().
lcstderr = lcstderr + oProcess:StandardError:ReadToEnd().

write a function in JES that will distinguish type of file is chosen

"Write a function that will obtain a file name (using pickAFile), and then recognise if it is a picture or a sound file, or even some other file type. The file should then be interpreted as either a picture, if its type is jpg (then print an appropriate message, then exit) or a sound, if its type is wav (then print an appropriate message, then exit), and if it is neither a picture nor a sound file, then an error message must be printed. This error message should include the type of the file (or the lack of a type, e.g. a file name that might not have a period in it, e.g. ducksjpg). Remember that file types can be 2, 3, 4 or even more letters long! "
So this is what I have figured out so far and it works:
def sortoutfiles():
f= pickAFile()
print f
filename=f
if filename.endswith (".jpg"):
print "It's a picture"
if filename.endswith (".wav"):
print " It's a sound"
else:
print"Oops! Did not choose a picture or a sound file"
For some reason the program doesnt work when I try to use rfind-get error message-invalid syntax on line 5
def sortoutfiles():
f= pickAFile()
print f
filename=f
if p=filename.rfind('.jpg'):
print "It's a picture"
if filename=f.rfind(".wav"):
print " It's a sound"
else:
print"Oops! Did not choose a picture or a sound file"
here
Can someone tell me what I am doing wrong in writing the program using rfind?
Apco 1P00?
Use rfind to figure out the file extension
f = pickAFile()
p = f.rfind('.jpg') #finds if the file ends in .jpg
s = f.rfind('.wav') #finds if the file ends in .wav
length = len(f) #finds the length of the file name
Use this as a foundation and go from here using if statements.
Recall the last lab.
>>> testString = 'abc DEf ghi ihg uVW xyz'
>>> print testString.find('k')
-1 #"Not found" can't be 0, so result is -1

Get path of selected Windows Explorer file in AutoIt

My AutoIt script worked as long as I used it via command line. There I could use $CmdLine[1] and pass a path as argument. Now I try to convert the script to a new method to avoid command line arguments.
You open an Explorer Window and select a file e.g C:\test.txt. After that you trigger the AutoIt function with CTRL+WIN+C. The script should look what file is selected in the active Explorer Window and retrieve the path C:\test.txt and assign it to $file variable.
This is my work-in-progress where I'm stuck.
Line 5 $CmdLine[1] needs to be changed to a secret function I don't know.
;Assign key combination "CTRL-WIN-C" to function "copyUNC"
HotKeySet("^#c", "CopyUNC")
;function to copy UNC path of selected Windows Explorer file/folder to clipboard
func CopyUNC()
$file = FileGetLongName($CmdLine[1]) ;THIS LINE NEEDS TO BE CHANGED
$drive = StringLeft($file, 2)
$UNCdrive = DriveMapGet($drive)
If $UNCdrive = "" Then
$UNCfile = $file
else
$UNCfile = $UNCdrive & StringTrimLeft($file, 2)
endif
ClipPut($UNCfile)
endfunc
;necessary loop so AutoIt script stays active and in Tray
While 1
Sleep(100)
WEnd
Q: How do I get the path of a selected file/folder from Windows Explorer into AutoIt v3.3.8.1?
Note #1: I don't want to use registry and right-click tricks to pass the argument
Note #2: If multiple files are selected just pass the first file. Don't overcomplicate things
CMDLINE[1] has nothing to do with what you want.
If you want to activate your script by hotkey AFTER manually selecting the file in Windows Explorer, you need to examine the Explorer window itself.
Here is the function to retrieve selected item in explorer
Func GetExplorerSelection()
Local $saveClip = ""
Local $filesFolders = ""
Local $handle = _WinAPI_GetForegroundWindow()
Local $className = _WinAPI_GetClassName($handle)
If $className = "ExploreWClass" Or $className = "CabinetWClass" Then
$saveClip = ClipGet()
Send("^c")
Sleep(50) ; give clipboard time to react
$filesFolders = ClipGet()
ClipPut($saveClip)
; test if $filesFolders contains #LF and split if so etc..
; code to call StringSplit() etc..
EndIf
EndFunc
maybe this
HotKeySet('{F8}','ccc')
Func ccc()
$ObjWindows = ObjCreate("Shell.Application").Windows()
For $i = 0 To $ObjWindows.Count -1
Local $w = $ObjWindows.Item($i)
Local $aSeLected = $w.Document.SelectedItems()
For $b = 0 To $aSeLected.Count -1
$x = $aSeLected.Item($b)
MsgBox(0,'',$x.Path&'_______'&$x.Name)
Next
Next
EndFunc
While 1
Sleep(100)
WEnd

Real-time output from engines in IPython parallel?

I am running a bunch of long-running tasks with IPython's great parallelization functionality.
How can I get real-time output from the ipengines' stdout in my IPython client?
E.g., I'm running dview.map_async(fun, lots_of_args) and fun prints to stdout. I would like to see the outputs as they are happening.
I know about AsyncResult.display_output(), but it's only available after all tasks have finished.
You can see stdout in the meantime by accessing AsyncResult.stdout, which will return a list of strings, which are the stdout from each engine.
The simplest case being:
print ar.stdout
You can wrap this in a simple function that prints stdout while you wait for the AsyncResult to complete:
import sys
import time
from IPython.display import clear_output
def wait_watching_stdout(ar, dt=1, truncate=1000):
while not ar.ready():
stdouts = ar.stdout
if not any(stdouts):
continue
# clear_output doesn't do much in terminal environments
clear_output()
print '-' * 30
print "%.3fs elapsed" % ar.elapsed
print ""
for eid, stdout in zip(ar._targets, ar.stdout):
if stdout:
print "[ stdout %2i ]\n%s" % (eid, stdout[-truncate:])
sys.stdout.flush()
time.sleep(dt)
An example notebook illustrating this function.
Now, if you are using older IPython, you may see an artificial restriction on access of the stdout attribute ('Result not ready' errors).
The information is available in the metadata, so you can still get at it while the task is not done:
rc.spin()
stdout = [ rc.metadata[msg_id]['stdout'] for msg_id in ar.msg_ids ]
Which is essentially the same thing that the ar.stdout attribute access does.
just in case somebody is still struggling with
getting ordinary print-outputs of the individual kernels:
I adapted minrk's answer such that i get the output of each
kernel as if it would have been a local one by constantly checking if the stdout of each kernel changes while the program is running.
asdf = dview.map_async(function, arguments)
# initialize a stdout0 array for comparison
stdout0 = asdf.stdout
while not asdf.ready():
# check if stdout changed for any kernel
if asdf.stdout != stdout0:
for i in range(0,len(asdf.stdout)):
if asdf.stdout[i] != stdout0[i]:
# print only new stdout's without previous message and remove '\n' at the end
print('kernel ' + str(i) + ': ' + asdf.stdout[i][len(stdout0[i]):-1])
# set stdout0 to last output for new comparison
stdout0 = asdf.stdout
else:
continue
asdf.get()
outputs will then be something like:
kernel0: message 1 from kernel 0
kernel1: message 1 from kernel 1
kernel0: message 2 from kernel 0
kernel0: message 3 from kernel 0
kernel1: message 2 from kernel 0
...