r/learnpython • u/forpyinpythings • Jul 26 '19
I am exactly 30 days into learning and this first thing I ever made, seriously thank you to this sub.
I have zero programming experience and 30 days ago I picked up Automate the Boring stuff. I am subbed to over 700 subs and I hop between accounts a lot. I decided to write something that would help me subscribe to all my subs every time I pick up a new account. I read here that PRAW is the way to mess around with reddit.
I know this has probably been made here a billion times, but its the first thing I've ever created by myself and I am so incredibly happy.
Thank you to everyone on this sub for all the encouragement, never posted before but I lurk heavy.
Please let me know if there is anyway I can improve/cleanup.
import praw
import openpyxl
import os
# open Reddit instance: Log inreddit = praw.Reddit(client_id='youridhere',client_secret='secretkeyhere',user_agent='agentname',username='username',password='redditpassword')
# Change directory to where your file is locatedos.chdir('/Users/path')
# Confirm you're in the right directoryos.getcwd()
# Open the excel file where subs are storedworkbook = openpyxl.load_workbook('allsubs.xlsx')
# Specify sheet that data is onsheet = workbook['Sheet1']
# Read data in each cell one by one
# Range of Cells that contain the subsfor subs in sheet['A1':'A732']:for cell in subs:
# Subscribe to each 'cell value' which is a sub's name
# Try/Except: For subs that are invite only or are currently quarantined
# Keep going if an exception is raised.try:print(reddit.subreddit(cell.value).subscribe())print('You have subscribed to: ' + cell.value)except Exception:passprint("\nAll done")
18
u/Xodus80 Jul 26 '19
That's very cool. I just started Crash course 2nd edition 4 days ago. I can't wait to get to where I can try things on my own like this. Thanks for sharing.
2
u/forpyinpythings Jul 26 '19
Im going to use that next, It really went into depth with functions which I still need a lot of practice on Its been suggested here that I create a function for this.
4
u/SimpleMath67 Jul 26 '19
I started this book a couple of weeks ago and just finished Chp 6. Crash Course has been more helpful than any other programming book I’ve tried to use. Makes things fun I’d say.
3
u/Tyler53121 Jul 26 '19
I’m on it right now too! I combine it with sololearn and some other apps for practice and reinforcement.
2
2
16
u/skochiefs Jul 26 '19
Have you figured out Appendix B? Running batch files from the command line? I am completely stuck.
7
u/forpyinpythings Jul 26 '19
For the most part yea, I’m using an apple computer so I’ve been using terminal and no batch files. Now that you mention it though I should probably learn that for windows too..
4
2
Jul 26 '19
If you need one-on-one help with that shoot me a pm
2
u/skochiefs Jul 28 '19
Thanks! I ended up getting it to work. Not entirely sure what was wrong, there seemed to be something wrong with my py.exe. I deleted and re-installed Python on my machine and it ended up working.
1
6
u/KezaGatame Jul 26 '19
I am quite a newbie here too so this is more like a curiosity question and how I would have done it, rather than advice
# Change directory to where your file is located
os.chdir('/Users/path')# Confirm you're in the right directory
os.getcwd()I bet you are using a script so I don't think os.getcwd() is necessary as you are declaring the path above with os.chdir('/Users/path'). As you only have one path confirming is an extra unnecesary step.
The only think that makes sense for this line os.getcwd() is if you are type line by line and want to see that you are in the right folder.
Other good practice is instead of putting your personal login data as a str you put in a variable that links them from another file. username='username' so if you pass the code you don't accidentally reveal personal login data. Some use a text file but if you have multiple account maybe an excel file.
I am still working through Automate the boring stuff, but I will give you my project idea I want to try with multiple Reddit's account.
Project Idea:
Create a script that will log in different Reddit's account
Run through the RUN box with only 2 parameters: script name and username
Create excel file with all the usernames, password, email, etc
From excel file find the user name and log in.
If there's already another account logged in, tell you which account is currrently logged in and ask if you want to log out. If the account is already logged in tell you "already log in".
5
u/forpyinpythings Jul 26 '19
Thank you I will for sure work on storing the login data more securely, sounds like a mistake I would definitely make.
I know the getcwd doesn't need to be there, its honestly there because when I went over that part in book, in my own practice, I kept forgetting to check where I was so I made it a habit to always check. Even if I think I know, just check!
To be honest I'm not sure I completely understand the project Idea, especially the 2nd bullet. Im interested in anything that helps me get better though. I have to repeat things so much to get it, and I feel like I'm forgetting if I'm not doing it all the time.
1
u/KezaGatame Jul 26 '19
Yeah getcwd is good to check but if you are running a script theres just no time to check, everything will probably run in 1 second. Is your code in a .py file (script) or are you typing line by line?
Well my project is about login in on different reddit's account with just running a little script without the manual labor of clicking log in, type username, type password. and if I want to log into antoher account i dont want to log out and do all over again.
the 2nd bullet is like this instead of opening the IDLE and run your script I can run it through the RUN box on Windows (or what ever the name) with just the python file name and my username. Al explain it on the book in an earlier chapter, and most of the projects he teach how to use it, one of the recent example I just saw is in chapter 11 that's how he runs the first example for the google map. Also check appendix B it's a little bit confusing but you might find it easier to grasp through a youtube video.
I just saw you are on MacOS, but on windows should look like this -> shortcut windows + R, type script.py username
1
u/forpyinpythings Jul 26 '19 edited Jul 26 '19
I got a copy of PyCharm and I'm writing everything in there. I really like the console because I can just run something from there when I'm done with it.
Ah! I think I understand the goal now, I think I could benefit from something like that.
Ive been able to run things using terminal but from what I've seen from another user in this thread, I should definitely figure out the windows portion too.
thanks again!
1
Jul 29 '19
I tried something very similar to this and the reddit host server gave my IP a 30 day ban so just be careful with how many requests you pull every second
2
u/KezaGatame Jul 30 '19
Interesting I will keep that in mind, I did heard this warning for webscrapping in general before. I would think I should be on the safe side, it's for personal use only and I only got less than 5 accounts and rarely use them all at the same time, like I have one for programming, another for movies and stuff and just log in when I want to leave a comment or upvote. Nothing like webscrapping or bots, yet.
Can you give so more details on your project, like how many requests was too much for your case. and was it a webscrapping project?
4
u/redeyerds Jul 26 '19
Are all those subbs tech related? I wouldn't mind seeing the list
9
u/forpyinpythings Jul 26 '19
I'm not gonna lie to you... only about half are legit subs.
The rest are all NSFW.
3
2
4
3
Jul 26 '19
Good job,
I suggest to create a class and initialize them via the __init__(): initialization method.
I also suggest placing the codes within custom functions with exception handling to ensure that the application will not crash nor become buggy when updated.
I also recommend to create a web server that gathers a live feed of your subscriber automatically and saves them into a file format such as CSV, HTML and/or JSON. Then it looks for the names along with pictures by using Pillow, a Python image manipulation API that will ensure integrity of the user and that is not a fake/dead account.
I also suggest to use Pandas to gather the data as it will make it easier than using openpyxl. Since it is an Excel file Pandas will know what to report if it cannot format it into the right way. It may be used to return the data the objects hold and subscribe without using Pillow.
I will say since you are a beginner i am impressed! Earned my respect as a Python Programmer.
What's your channel? PM me it, i want to subscribe.
+rep
2
u/forpyinpythings Jul 26 '19 edited Jul 26 '19
I haven't quite reached the classes stage yet. I did notice that its part of OOP.
I think I read here once that its important to focus on the basics first before moving to OOP, so I've been doing that. Data Structure/loops/conditionals and functions.
I do like the function idea though. I will try to create a function from this!
Thank you I really appreciate that!What do you mean by channel?
Also, im not familiar with pandas outside of the animal community, do you have a good resource to learn about it?
1
Jul 27 '19
If you have not reached the OOP points in Python then i suggest you to learn as much as basics as you can as the OOP depends with the basics and may include some advanced such as creating a server.
You are more than welcome, if you need any help just let me know, exception handling may be a bit advanced but it will help to keep your program running if even a user enters a wrong value.
I suggest going onto this guy's tutorial series "https://www.udemy.com/the-python-mega-course/"
He explains from the basics towards GUI and Pandas. Pandas is like the one your using but more powerful and dynamic, such as you may export the data into an HTML format and much more as said. It allows you to export them into a server as well. A good video is "https://www.youtube.com/watch?v=Iqjy9UqKKuo"
SentDex will clarify more than the books such as the API's used in real world applications.
Hope it helps and let me know if i can be a help :))
By channel i meant YouTube channel
3
u/christophski Jul 26 '19
One point I would make is with your try/except. Always try to be as specific as possible with your exceptions, to ensure you aren't also catching other unexpected exceptions. ie, you are trying to catch an exception for invite only/quarantined subs. But what if a different error is raised? You will never know because except Exception catches almost everything.
1
u/forpyinpythings Jul 26 '19
You're absolutely right, I caught 2 different http errors when I tried to sub to a sub that didn't exist and another for quarantined and beta subs. I didn't really know how to specify the errors I wanted to catch.
Would you happen to know a good reference guide that would explain try/except a bit more in-depth?
1
u/KezaGatame Jul 26 '19
Can you show us a simple example?
he would have to know the errors coming for invite only/quarantined which probably will through one error, how do you plan ahead for errors you are not expecting?
1
u/christophski Jul 26 '19
Well, that is exactly it. The errors we aren't expecting should raise as normal and quit the program.
try: m = some_dict["some_key"] print(m.title()) except Execption: passSo here, if m is None, the title function will raise a TypeError. If m is none, we just want to continue without any issue. We've used Exception. But what if "some_key" doesn't exist in "some_dict"? It means there is something wrong with our source data and we want to know that. However in this situation the KeyError will be caught by the try/except and we will never know that the error occurred. The most important thing about using try/excepts to me is knowing what error you are trying to catch. It is also part of pep8 to not use very general exceptions, especially bare excepts.
4
1
u/sjbland Jul 26 '19
Nice! You could save yourself a bit of hassle by saving your list as a CSV so yo don't need to use openpyxl or pandas etc?
1
u/forpyinpythings Jul 26 '19
Good idea!
Do you know a resource that explains how to work with CSVs or is it similar to working with an xls file?
1
u/sjbland Jul 26 '19
Less involved than dealing with xlsx files I find. It's built into Python by default. Enjoy!
1
u/forpyinpythings Jul 26 '19
Thank you!
1
u/sjbland Jul 26 '19
Not a problem! Best way to learn is to ask. I actually quickly re-factored your script this morning whilst I was having my breakfast. I'll PM you later when I'm in from work so you can have a look.
1
1
u/al_mc_y Jul 26 '19
Great stuff! Congratulations. I noticed that you've got a fixed cell range for the subs in the worksheet. I can't recall the exact commands/syntax (and i'm doing this from my phone on the commute home) - for the '''subs in sheet''' you could make the cell range dynamic, so it picks up the last used row. That way if/when you add more entries you won't need to go back and update the reference manually 😁
1
1
u/ItsAFineWorld Jul 26 '19
How much time have you devoted into the book? Have you completed all of it?
1
u/forpyinpythings Jul 26 '19
I watch the videos and use the book.
I go over each section while I write down the code and my own notes under it directly into PyCharm.
Usually about 2-3 hours a day and as long as I can go on the weekends.
I completed the book but still refer to it and my notes when I'm practicing.
3
u/LennyKrabigs Jul 26 '19
Im developing a big project its a bot for a game, these subreddit is helping me a lot. thank you and keep the good work :3
2
2
u/Ryman12320 Jul 26 '19
This isnt about your program but it's just some stuff I have found very helpful to me and i just wanna share.
Python Tutorial for Beginners [Full Course] 2019.
it's a nice course going thru a lot in a few hours, he also includes three mini projects to show what's possible with python
Jupyter Notebook.
Is a web based environment that contains live code and allows you to easily create graphs/visualize your data.(there is also JupyterLab that's can support more of the possibilities that you can do with python)
Codewars.com
It's a coding website that has a huge range of coding challenges in many different languages created by its community
2
u/maddruid Jul 26 '19
Very nice. FYI - You could switch to yaml (PyYAML) to store your credentials and the list of subs. This would greatly simplify the script and your maintenance workflow by dropping excel. PyYAML also provides a safe_load(file) function that prevents exploits being loaded from the yaml file.
2
1
u/jpf5046 Jul 26 '19
Good to see it. I would have used pandas.read_excel instead of openpyxl to read the data. no reason other than pandas is more popular than openpyxl.
0
u/gschizas gschizas Jul 26 '19
pandas uses openpyxl internally (especially when writing to Excel files).
1
1
u/arsamsarabi Jul 26 '19
Well done dude, you can use https://carbon.now.sh to share your code snippets
1
u/Phluxxed Jul 26 '19
Best feeling ever right?!
I wrote my first script the other night that hooks into the LogMeIn API, sends my credentials (after converting to base64) and then pulls a bunch of user details, which then into a csv using pandas that I can use in an Excel spreadsheet to vlookup some stuff.
I was so insanely stoked when I got it to work 😎
1
1
1
u/XChrisUnknownX Jul 26 '19
Everybody’s first projects seem so much more inspired and complex than mine.
Great job OP!
2
u/cobalt8 Jul 26 '19
Never judge your progress based on that of others. You're in for a world of disappointment if you do. If you ever feel down, just remember that working towards a project of any level of difficulty already puts you ahead of the millions in the world that don't even know where to start.
1
u/CaptRupee Jul 26 '19
Hey I started with python last week :D I usually do C++ or C# but I love python and cool lil program haha!
Some Feedback:
- your naming convention is good
- You commented your work, A+ ( I know people who have 10 years of experience and still dont comment -__-)
- personally I think this is a good first project, my advice would be to try and think how you can add more functionality, maybe user input? What about and interface using tkinter that tells you what you are subscribed to?
Good work OP! Cant wait to see more!
1
u/cobalt8 Jul 26 '19
Great job creating something useful for your first project! Next, I recommend you spend a little bit of time learning git and setting up an account on GitHub or gitlab. Not only will it make it easier to share your code here and in other places, it will also help you version your code while you're writing it, which you will undoubtedly find invaluable when you work on more complicated projects.
1
1
u/FredoRicko Jul 27 '19
Wow! This is great. I also began learning a few weeks ago and I'm using both the python crash course and the automate the boring stuff with python books. I'm working with Tkinter library to build my first project. A simple calculator app.
0
Jul 26 '19
[deleted]
1
u/forpyinpythings Jul 26 '19
I used the Udemy course, got it on sale and the book.
https://www.udemy.com/automate/
I got it on sale for $11
and the book here
36
u/YAYYYYYYYYY Jul 26 '19
Awesome! Love to see it