Cannot loop over an array [duplicate] - python

This question already has an answer here:
Access specific information within worklogs in jira-python
(1 answer)
Closed 5 years ago.
I'm trying to insert the following worklog JSON fields that are part of an array using Python however I don't seem to be able to loop over an array in Python.
See code snippet below:
try:
worklogs_to_insert = []
for i in issue.fields.worklog["worklogs"]:
worklogs_to_insert.append(i)
except AttributeError as e:
log.info("Something went wrong when processing worklogs. :(")
log.info(e)
I am getting the following error when script is run:
Something went wrong when processing worklogs. :(
type object 'PropertyHolder' has no attribute 'worklog'

try using
for i in issue.fields.worklog.raw["worklogs"]

Related

Python - Requests module "response.text" [duplicate]

This question already has an answer here:
How to extract values from a Python request
(1 answer)
Closed 6 months ago.
How do I get a specific element from requests response.text
{"status":"success","data":{"id":30815925}}
im need to get ID from that output
You can import the json package and simply do
import json
id = json.loads(response.text)["data"]["id"]
This will convert response.text from a string to a python dictionary, and the id will be inside the variable id

Send a formated list with pushover on python [duplicate]

This question already has answers here:
How to concatenate (join) items in a list to a single string
(11 answers)
Closed 2 years ago.
I'm relatively new to python,
I built a webscraper that gets the top posts of a website and stores them in a list in python like this:
T = ["post1","post2","post3,"post4"]
To send the push notification with pushover I installed the pushover module that works like this:
from pushover import Pushover
po = Pushover("My App Token")
po.user("My User Token")
msg = po.msg("Hello, World!")
po.send(msg)
I want to send the list as a message with format, like this:
Top Posts:
1. post 1
2. post 2
3. post 3
4. post 4
I tried this:
msg = po.msg("<b>Top Posts:</b>\n\n1. "+T[0]+"\n"+"2. "+T[1]+"\n"+"3. "+T[2]+"\n"+"4. "+T[3]")
The above solution works, however the number of posts will be variable so that's not a viable solution.
What can I do to send the message with the correct formatting knowing that the number of posts in the list will vary from time to time?
Using str.join and a comprehension using enumerate:
msg = po.msg("<b>Top Posts:</b>\n\n" + '\n'.join(f'{n}. s {n}' for n, s in enumerate(T, 1)))

Python switch between users [duplicate]

This question already has answers here:
Is there a portable way to get the current username in Python?
(15 answers)
Closed 2 years ago.
I am trying to implement a switch at the beginning of my code, in order to change the working directory based on who's running the code. In Stata, this exists and looks like the following:
if "`c(username)'" == "albert" {
local PATH "/home/albert/Dropbox/Project1"
}
else if "`c(username)'" == "charlene" {
local PATH "C:/Users/charlene/Documents/Dropbox/Project1"
}
I am just missing the "user" part in python. Does anyone knows if that even exists ?
Would the getpass.getuser() function do the trick?

Python requests with timer and string replace [duplicate]

This question already has answers here:
Print to the same line and not a new line? [duplicate]
(19 answers)
Closed 3 years ago.
I am using an API where I can fetch data with. From the data output I am trying to get specific portions so I can place it nicely in a formatted text.
I want to fetch the data every 5 seconds, so I get fresh info. I do not want that the data is prompted below the output from the first run, but rather replace the current value(s) for the updated value(s).
As I'm pretty bad with python, I hope someone can give me some advice.
import requests
import threading
def dostuff()
threading.Timer(5.0, dostuff).start()
r = requests.get('https://api')
data = r.json()
print("Amount:", data['amount'])
print("Games played:", data['matches'])
dostuff()
This works fine. It just keeps posting the output under each other.
I wish to have everything static, except the data['amount'], and data['matches'], which should keep updating without actually posting it on newlines. I have tried resolving this by clearning the screen, but that is not the desired solution.
Just add end='\r' to your print statement:
import requests
import threading
import random
def dostuff():
threading.Timer(1.0, dostuff).start()
# replaced as actual api not posted
data = {
'amount': round(random.random(), 2),
"matches": round(random.random(), 2)
}
print("Amount: {} Games played: {}".format(
data['amount'],
data['matches']
), end='\r')
dostuff()

Python: pass an item's value instead of it's name [duplicate]

This question already has answers here:
How to access (get or set) object attribute given string corresponding to name of that attribute
(3 answers)
Closed 8 years ago.
This has to be asked somewhere already, but I don't know the right words to find or frame it. So please bear with me.
This code fragment:
code = 'VegCode'
d = {}
codes = foo_func
for item in codes:
print item.code
Results in:
RuntimeError: Row: Field code does not exist
if I change it like this, it will work, but I don't want to hard code the variable name:
for item in codes:
print item.VegCode
How do I pass the value of code to the item object instead of it's name? (and please tell me what key words would have led to an answer!)
Use getattr: getattr(item, code)
Keywords: how to access object's attribute by its name

Categories

Resources