Python Shelve like requirement [closed] - python

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I want to store some kind of persistent tracking to my application. Like for example ,
application.py supports 3 arguments, --firstarg --secondarg --thirdarg.
user can execute application.py using either one of the argument. I want to provide a feature where in user can track that he has already completed running the firstarg. In order to achieve this, i wanted to store a file called status.log, where the tracker will be stored.
Initially, status.log has
firstarg : 0
secondarg : 0
thirdarg : 0
once the user executes the first arg, it should turn the line , firstarg : 1
so when users wants, he can check if he has already completed running the firstarg or not.
Is it possible ?
I tried shelve, its not working for me for some reason. I am not seeing any logs written to the file.
Thanks.

I'd say use a JSON file as a persistent store and use the load and dump methods for reads and writes.
The JSON method is built in so all you need is to import it and use it:
import json
data_file = '/path/to/file'
# Load current state from file
contents = json.load(data_file)
# Do something
# ....
# ....
# Change values
contents['firstarg'] = firstarg
# Save to file
json.dump(contents, data_file)
Since you don't have a code sample, this is a simple approach

Related

Looping a function with its input being a url [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
So I am trying to get into python, and am using other examples that I find online to understand certain functions better.
I found a post online that shared a way to check prices on an item through CamelCamelCamel.
They had it set to request from a specific url, so I decided to change it to userinput instead.
How can I just simply loop this function?
It runs fine afaik once, but after the inital process i get 'Process finished with exit code 0', which isn't necessarily a problem.
For the script to perform how I would like it to. It would be nice if there was a break from maybe, 'quit' or something, but after it processes the URL that was given, I would like it to request for a new URL.
Im sure theres a way to check for a specific url, IE this should only work for Camelcamelcamel, so to limit to only that domain.
Im more familiar with Batch, and have kinda gotten away with using batch to run my python files to circumvent what I dont understand.
Personally if I could . . .
I would just mark the funct as 'top:'
and put goto top at the bottom of the script.
from bs4 import BeautifulSoup
import requests
print("Enter CamelCamelCamel Link: ")
plink = input("")
headers = {'User-Agent': 'Mozilla/5.0'}
r = requests.get(plink,headers=headers)
data = r.text
soup = BeautifulSoup(data,'html.parser')
table_data = soup.select('table.product_pane tbody tr td')
hprice = table_data[1].string
hdate = table_data[2].string
lprice = table_data[7].string
ldate = table_data[8].string
print ('High price-',hprice)
print ("[H-Date]", hdate)
print ('---------------')
print ('Low price-',lprice)
print ("[L-Date]", ldate)
Also how could I find the difference from the date I obtain from either hdate or ldate, from today/now. How the dates I parsed they're strings and I got. TypeError: unsupported operand type(s) for +=: 'int' and 'str'.
This is really just for learning, any example works, It doesnt have to be that site in specific.
In Python, you have access to several different types of looping control structures, including:
while statements
while (condition) # Will execute until condition is no longer True (or until break is called)
<statements to execute while looping>
for statements
for i in range(10) # Will execute 10 times (or until break is called)
<statements to execute while looping>
Each one has its strengths and weaknesses, and the documentation at Python.org is very thorough but easy to assimilate.
https://docs.python.org/3/tutorial/controlflow.html

Python request convert string to JSON [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm using the requests library in Python to do a post request, but I'm having a problem when I read a value from a spreadsheet.
The following code works (returns a 201 status code):
url = 'http://myport:8092//api/Accounts/1000/Users'
item = {"firstName": "John", "lastName": "Smith", "userName": "JSmith"}
r = requests.post(url, json = item)
print(r.status_code)
As soon as I read "item" from a cell in a spreadsheet, a 501 error code gets returned. When I print out "item" after reading it from the spreadsheet, the output matches the value for item shown above.
I haven't been able to find a solution, the only thing I can think of is that the problem is that it's being read as a string?
Do I need to convert it into a json object before I run the post?
501 is the error code for not implemented. It looks like the url you're sending to doesn't accept post requests. Is the url correct?

Python: Writing lists to .csv file [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I’m teaching myself programming, using Python as my initial weapon of choice.
I have learnt a few basics and decided to set myself the challenge of asking the user for a list of names, adding the names to a list and then finally writing the names to a .csv file.
Below is my code. It works.
My question is what would you do differently, i.e. how could this code be improved for readability and efficiency. Would you approach the situation differently, structure it differently, call different functions? I am interested in, and would appreciate a great deal, the feedback from more experienced programmers.
In particular, I find certain parts clunky; such as having to specify to the user the required format for data entry. If I were to simply request the data (name age location) without the commas however, then each record, when written to .csv, would simply end up as one record per cell (Excel) – this is not the desired result.
#Requesting user input.
guestNames = input("Please enter the names of your guests, one at a time.\n"\
"Once you have finished entering the information, please type the word \"Done\".\n"\
"Please enter your names in the following format (Name, Age, Location). ").capitalize()
guestList.append(guestNames)
while guestNames.lower() != "done".lower() :
guestNames = input("Please enter the name of your " + guestNumber[number] + " guest: ").capitalize()
guestList.append(guestNames)
number += 1
#Sorting the list.
guestList.sort()
guestList.remove("Done")
#Creating .csv file.
guestFile = open("guestList.csv","w")
guestFile.close()
#Writing to file.
for entries in guestList :
guestFile = open("guestList.csv","a")
guestFile.write(entries)
guestFile.write("\n")
guestFile.close()
I try to write down your demands:
Parse the input string according to its structure (whatever) and save results into a list
Format the result into CSV-format string
write the string to a CSV file
First of all, I would highly recommend you to read the a Python string operation and formatting tutorial like Google Developer Tutorial. When you understand the basic operation, have a look at official documentation to see available string processing methods in Python.
Your logic to write the code is right, but there are two meaningless lines:
while guestNames.lower() != "done".lower()
It's not necessary to lower "done" since it is already lower-case.
for entries in guestList :
guestFile = open("guestList.csv","a")
Here you open and close the questList.csv every loop, which is useless and costly. You could open the file at the beginning, then save all lines with a for loop, and close it at the end.
This is a sample using the same logic and different input format:
print('some notification at the beginning')
while true:
guestNames = input("Please enter the name of your " + guestNumber[number] + " guest: ").capitalize()
if guestNames == 'Done':
# Jump out of the loop if user says done
break
else:
# Assume user input 'name age location', replace all space with commas
guestList.append(guestNames.replace(' ', ','))
number += 1
guestList.sort()
# the with keyword will close the guestFile at the end
with open("guestList.csv","w") as guestFile:
guestFile.write('your headers\n')
for entries in guestList:
guestFile.write('%s\n' % entries)
Be aware that there are many ways to fulfil your demands, with different logics and methodologies.

Python all objects changed if one is [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm having a peculiar problem with values inside an object being set to whatever I set that variable to in later new instances. Let me try to explain first with an example of the kind of results I'm getting given doc.python.org's example on how to use class objects.
b = Dog("Buddy")
e = Dog("Spot")
b.Name
e.Name
for me gives an output of
Spot
Spot
With the help of some debug lines, I've found that this phenomenon occurs when coming out of for loop. So here is my actual code and it's results:
tempTray = Tray("{0}:{1}".format(UnitName, TrayName))
for eachDish in range(len(tempTray.GridSizes)):
if Row1.find("[") > -1:
Parse = Row1[Row1.find("[")+1:Row1.find("]")]
Row1 = Row1[Row1.find("]")+1:]
elif Row2.find("[") > -1:
Parse = Row2[Row2.find("[")+1:Row2.find("]")]
Row2 = Row2[Row2.find("]")+1:]
elif Row3.find("[") > -1:
Parse = Row3[Row3.find("[")+1:Row3.find("]")]
Row3 = Row3[Row3.find("]")+1:]
if Parse != "Empty":
tempTray.GridSizes[eachDish] = Parse[:Parse.find(" ")]
tempTray.GridColors[eachDish] = self.Colors[Parse[Parse.find(" ")+1:]]
# Check point 1
self.AllTrays.append(tempTray)
# Check point 2
At # Check point 1 I have a debug print test that writes the contents of tempTray's 2 values, and the contain the correct information at this point, but if I check the same thing again at # Check point 2, now they become set to whatever is in the last tray loaded by the xml file (and I've tried looking at all 4 trays, not just self.AllTrays[0], they all have the same values) I've also ruled out that my xml file is saved with changes current.
Any solutions or workarounds? I've come across this before but without consistency (a card game where the card data loaded from a file correctly but each player was being set to the name "Player 2" and their score values both went up and down if I changed either one of their scores)
It'd be good to see the actual code for your Dog class's definition. Chances are you have made Name a class variable as opposed to an instance variable (the Python documentation actually uses a Dog class to show the difference).
The Python documentation actually has a great short and sweet explanation of Class and Instance Variables; so, I suggest you read it and ask more questions if need be.

Get value from 2nd list based on ID from 1st list in Python [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm a beginner in Python and have a file i've read in that has an Market_ID field. While looping over this file (list), I need to access the Market_name in a 2nd file (Market_ID,Market_Name).
What's the best place for me to start? I can give more detail on what the program is doing if necessary.
The files(lists) are laid out as follows:
File1: Cust_ID, Market_ID, Cust_Name, IsNew
File2: Market_ID, Market_Name
My main loop is over File1. I need to be able to access the Market_Name from File2 to be able to place it in a new file i'm creating from data in File1. Hope that helps.
If the files are not too big (a few megabytes) you could store each item in a dict() using the Market_ID as key.
This looks like data drom a database - if you are familiar with
relational databases and their use you could insert each file into a
separate table and then perform queries. Python has an interface to
sqlite in its standard library.
For solving this quickly I suggest to use dicts though.
BY -- sleeplessnerd
More about dictionaries,
More about sqlite
file2 = open("/path/to/file2", "r")
market_names = {}
for line in file2:
fields = line.split(",")
market_names[int(fields[0])] = fields[1]
file2.close()
file1 = open("/path/to/file1", "r")
for line in file1:
fields = line.split(",")
market_name = market_names[int(fields[1])]
# do what ever you want with the Market_Name associated with
# the Market_ID contained in this line
file1.close()
If the files are not too big (a few megabytes) you could store each item in a dict() using the Market_ID as key.
This looks like data drom a database - if you are familiar with relational databases and their use you could insert each file into a separate table and then perform queries. Python has an interface to sqlite in its standard library.
For solving this quickly I suggest to use dicts though.
Hmm, could you please supply more details?
When you say file(list) do you mean that you've created a list that contains all the data you need from the first file? what about the second file?
If they are both lists than something like this would work:
for market_id in flie1_list:
for pair in file2_list:
if pair[0] == market_id:
market_name = pair[1]
break
<keep doing whatever it is you need to do in first loop>
Note - I'm fairly a beginner as well, and it's my first answer on this site. Go easy ;)
I'm not up on my python, but conceptually, what you'll probably want to do is read the second file into a dictionary first and then look up the id in the dictionary to get the associated name. Alternatively, if the ids are numeric and more-or-less dense, you could just read them into a regular array.

Categories

Resources