How to repeat openeing tabs? - python

Here is my code:
times_to_repeat = 10
while times_to_repeat > 0:
import string
import random
S = 6
ran = ''.join(random.choices(string.ascii_lowercase + string.digits, k=S))
x = ran
print("The randomly generated string is : " + str(ran))
import webbrowser
webbrowser.open("prnt.sc/" + x)
times_to_repeat -= 1
I'm trying to do the prnt.sc challenge, and I want to be able to open 10 tabs of random strings, to speed up the process. My problem is that it only opens one tab when I run it, but it prints my random string ten times. Both are on a loop, so shouldn't both things repeat? I get "your random string is (whatever the string is) 10 times, but my browser only opens 1 tab. I'm quite new to python so I don't know a whole lot about loops.

Currently, your code seems to be opening 10 different browsers.
I'm not absolutely sure about how but seems that the internal call of webbrowser.open("prnt.sc/" + x) is making the OS don't be able to use the currently active browser, since prnt.sc/ is not a web URL, because the https:// part is missing.
Just add the protocol and it will work:
while times_to_repeat > 0:
import string
import random
S = 6
ran = ''.join(random.choices(string.ascii_lowercase + string.digits, k=S))
x = ran
print("The randomly generated string is : " + str(ran))
import webbrowser
webbrowser.open("https://prnt.sc/" + x)
times_to_repeat -= 1
Nevertheless, your code loop is a bit strange and a bit difficult to read. Also, importing libraries on a while loop is not a really good practice.
import string
import random
import webbrowser
S = 6
times_to_repeat = 4
for x in range(0, times_to_repeat):
ran = ''.join(random.sample(string.ascii_lowercase, S))
print("The randomly generated string is : " + str(ran))
webbrowser.open("https://prnt.sc/" + ran)

Related

How to change the sleep function of time module in python

from time import sleep
a = 30
text = ""
source = pd.read_csv("questions.csv")
questions = source["questions"]
for i in questions:
try:
print(i)
text = text.join(i)
except TypeError:
pass
print(len(text) / 60 / a)
def plan3():#env):
for i in range(len(text)):
b = text[(i * a):(i * a) + a]
print(b, end="")
sleep(1)
plan3()
I am trying to make ^ work, but the screen doesn't update until I manually cancel the program with KeyboardInterrupt.
I believe it is due to the way sleep() is coded that makes it perform the function for the required amount of time, so I am unable to change this property.
The csv file has a database of questions, it can be swapped for a large string value and still it will not update "dynamically", if I am using the word correctly.
I need the questions to print like a printer, line by line on the screen on the TERMINAL.
setting print("",flush = True) didn't solve for python 3.8

Output random hex values from within a range in python [duplicate]

This question already has answers here:
How can I get new results from randint while in a loop?
(2 answers)
Closed 3 years ago.
I am able to generate random hex values in a specific range using the code below, but I get the same random value on each line if i set my counter to more than 1. I'm guessing I need a loop, I have tried with "for x in range" but my implementation must be wrong as it overflows. I'm new to python and have searched for days but can't seem to find how to implement it correctly.
import random
import sys
#ran = random.randrange(2**64)
ran = random.randrange(0x8000000000000000, 0xFFFFFFFFFFFFFFFF)
myhex = "%064x" % ran
#limit string to 64 characters
myhex = myhex[:64]
counter = 0
file = open('output.txt', 'w')
sys.stdout = file
for result in myhex:
print(myhex)
counter += 1
if counter > 10:
break
As pointed out in the comments, you're generating the random number only once. To have a new random value for each iteration, you need to put the generation code in the loop as follows:
# ... your imports
with open('output.txt', 'w') as f:
for _ in range(10):
ran = random.randrange(0x8000000000000000, 0xFFFFFFFFFFFFFFFF)
myhex = "%064x" % ran
#limit string to 64 characters
myhex = myhex[:64]
f.write(myhex)
f.write("\n")
Also, if you want to dump the results in a file, a better approach is to write directly to the file without changing sys.stdout, as done in the above code.

VicBot Dice Roller (Python 2.7)

I'm going to be honest: I don't really know what I'm doing.
I'd like to make it so VicBot (for Python 2.7) can "roll" "dice" on the command "/roll xdy" with x being the number of die and y being the number of sides on those die.
So, more directly I need to be able to request x variables ≥y, and have them displayed "(variable) + (variable) = (sum)"
All of VicBot can be found here: https://github.com/Vicyorus/VicBot
(In case you were wondering: I did accidentally post this question before I was finished.)
I don't know much about your chatbot, nor do I really want to dig through all the code you've included in your question (it's not even clear to me if any of it is code that you've written, rather than example code that comes with the bot).
What I can do is address the die rolling stuff. That's pretty easy. All you need is Python's random module and some string manipulation and formatting code.
import random
def roll_dice(dice_string):
"""Parse a string like "3d6" and return a string showing the die rolls and their sum"""
number_of_dice, number_of_sides = map(int, dice_string.split("d"))
rolls = [random.randint(1, number_of_sides) for _ in range(number_of_dice)]
output_string = "{} = {}".format(" + ".join(map(str(rolls)), sum(rolls))
return output_string
Example output:
>>> roll_dice("5d6")
'6 + 6 + 5 + 5 + 6 = 28'
>>> roll_dice("5d6")
'1 + 5 + 1 + 2 + 2 = 11'
>>> roll_dice("3d100")
'16 + 83 + 56 = 155'
>>> roll_dice("1d20")
'18 = 18'
Hopefully the code is pretty self explanatory. The four statements in the function each do one thing: parsing the input, generating the requested random numbers, formatting them into a string for output, and finally returning the string. The second line, which does the actual random number generation might be useful to extract as a separate function (taking integer arguments and returning a list of integers).

Python (Pywin32) Referencing Own Cell/Horizontal Movement

So please don't tell me to google or research or read anything, I've been doing that for the past couple of days and will get annoyed if I see someone say that again.
My problem: I am using pywin32 and python 2.7.8 to communicate with (an already existing) excel sheet. I use it to log my hours worked and money earned, etc. I have it functioning to the point that I can open the workbook, find the next empty cell under my existing entries and write the date in that cell. My problem lies in the fact that I need to navigate horizontally. I want the program to run automatically so I will not always know the number of the cell. For example, my current cell is 18,1. I need to move to 18,2 18,3 18,4 and 18,5. But next time I run the script I may need 19,2... etc.
How can I do this? Is there a way to return the current cell or something?
code:
import win32com.client as win32
import os, time
xl = win32.Dispatch('Excel.Application')
xl.visible = True
xl.Workbooks.Open(os.path.join('C:\\Users\\[REDACTED]\\Desktop', '[REDACTED].xls'))
xlSheet = xl.Sheets(1)
activecell = xlSheet.Cells(1,1)
def GetEmptyCell():
global activecell
activecell = xlSheet.Cells(1,1)
for c in range(1,99,1):
if activecell.Value == None:
print 'Empty cell'
activecell = xlSheet.Cells(c,1)
print '(' + str(c) + ',1)'
return activecell
elif activecell.Value != None:
c += 1
activecell = xlSheet.Cells(c,1)
print 'Full cell, next'
GetEmptyCell()
def WriteToEmpty():
global activecell
global HoursWorked
global GrossIncome
global NetIncome
HoursWorked = raw_input('Input amount of hours worked: ')
GrossIncome = float(HoursWorked) * 9.15
NetIncome = float(GrossIncome) * 0.86233
print 'Money Made: ' + str(GrossIncome) + ' Take Home: ' + str(NetIncome)
activecell.Value = time.strftime('%a') + ' ' + time.strftime('%m') + '/' + time.strftime('%d')
#HELP FROM HERE
WriteToEmpty()``
There are dozens of ways to acheive what you want. If you have contiguous data in column A you could use something like xl.range("A1").end(xldown).offset(1,0).address to get the address of the first cell in the next empty row. Or you could use xl.range("A1").currentregion and offset from there.
Personally i'd probably just put the current region into an array and work from there, then dump the array back to the sheet, but thats always my preference, most people seem to prefer to work on the sheet.

generating promotion code using python

By using python language, what would be a clever / efficient way of generating promotion codes.
Like to be used for generating special numbers for discount coupons.
like: 1027828-1
Thanks
The following isn't particularly pythonic or particularly efficient, but it might suffice:
import random
def get_promo_code(num_chars):
code_chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
code = ''
for i in range(0, num_chars):
slice_start = random.randint(0, len(code_chars) - 1)
code += code_chars[slice_start: slice_start + 1]
return code
1027828-1 is extremely small. An attacker can make a ~million guesses using only a couple lines of code and maybe a few days.
This is a good way to produce a hard to predict number using python, it works under linux and windows. It is base64'ed for binary safety, depending what you are doing with it you might want to urllib.urlencode() but I would avoid base10 because it doesn't store as much information.
import os
import base64
def secure_rand(len=8):
token=os.urandom(len)
return base64.b64encode(token)
print(secure_rand())
As a side note this is generating a full byte, which is base256. 256^8 is 18446744073709551616 which should be large enough.
As it was pointed out base64 isn't a very good token for humans to use. Consider an alternate encoding like url-safe base64 or perhaps humanhash as they would be easier to type in.
if you need a 6-digit # you could do this until you found a unique value:
import random
print str(random.randint(100000, 999999))
or go sequentially...
Try this:
import random
coupon = open("coupons.txt", "a")
def generate(amount):
for x in range(0, amount):
a = random.randint(1000, 9999)
a = str(a)
b = random.randint(1000, 9999)
b = str(b)
c = random.randint(1000, 9999)
c = str(c)
total = ""
total = str(total)
total = a + " " + b + " " + c
coupon.write(total)
coupon.write("\n")
amount = int(input("How many coupons do you want to generate: "))
generate(amount)
coupon.close()
print("\nCode's have been generated!")
You can make the coupons as long as you want. They save into a txt file called coupons.txt also.
I've come up with an answer for this that I think is fairly clever, but relies on a couple of assumptions that might not be true for your situation.
The resulting code is purely numeric.
The resulting code is technically variable-length; [10, 20].
If these work for you, then so might this solution:
def code(seed = None):
if (not seed) or (type(seed) != str) or (len(seed) < 10):
seed = str(uuid.uuid4())[:10]
code = ""
for character in seed:
value = str(ord(character))
code += value
return code[:20]
In this function, a string-typed seed is used as the base of the code. For each character in the string, convert it into its ASCII representation, then append it to the code.
By default, the function yields codes like this: '97534957569756524557', and can be invoked with any arbitrary seed. For example...
code("pcperini's answer") == '11299112101114105110'
code(str(time.time())) == '49524956514950505257'

Categories