This is my first time asking a question. I am just starting to get into programming, so i am beginning with Python. So I've basically got a random number generator inside of a while loop, thats inside of my "r()' function. What I want to do is take all of the numbers (basically like an infinite amount until i shut down idle) and put them into a text file. Now i have looked for this on the world wide web and have found solutions for this, but on a windows computer. I have a mac with python 2.7. ANY HELP IS VERY MUCH APPRECIATED! My current code is below
from random import randrange
def r():
while True:
print randrange(1,10)
The general idea is to open the file, write to it (as many times as you need to), and close it. This is explained in the tutorial under Reading and Writing Files.
The with statement (described toward the end of that section) is a great way to make sure the file always gets closed. (Otherwise, when you stopped your script with ^C, the file might end up missing the last few hundred bytes, and you'd have to use try/finally to handle that properly.)
The write method on files isn't quite as "friendly" as the print statement—it doesn't automatically convert things to strings, add a newline at the end, accept multiple comma-separated values, etc. So usually, you'll want to use string formatting to do that stuff for you.
For example:
def r():
with open('textfile.txt', 'w') as f:
while True:
f.write('{}\n'.format(randrange(1, 10)))
You'll need to call the function and then redirect the output to a file or use the python API to write to a file. Your whole script could be:
from random import randrange
def r():
while True:
print randrange(1,10)
r()
Then you can run python script_name.py > output.txt
If you'd like to use the python API to write to a file, your script should be modified to something like the following:
from random import randrange
def r():
with open('somefile.txt', 'w') as f:
while True:
f.write('{}\n'.format(randrange(1,10)))
r()
The with statement will take care of closing the file instance appropriately.
Related
Hi I have a problem that I cannot seem to find any solution for.
(Maybe i'm just horrible at phrasing searches correctly in english)
I'm trying to execute a binary from python using pwntools and reading its output completely before sending some input myself.
The output from my binary is as follows:
Testmessage1
Testmessage2
Enter input: <binary expects me to input stuff here>
Where I would like to read the first line, the second line and the output part of the third line (with ':' being the last character).
The third line of the output does not contain a newline at the end and expects the user to make an input directly. However, I'm not able to read the output contents that the third line starts with, no matter what I try.
My current way of trying to achieve this:
from pwn import *
io = process("./testbin")
print io.recvline()
print io.recvline()
print io.recvuntil(":", timeout=1) # this get's stuck if I dont use a timeout
...
# maybe sending data here
# io.send(....)
io.close()
Do I missunderstand something about stdin and stdout? Is "Enter input:" of the third line not part of the output that I should be able to receive before making an input?
Thanks in advance
I finally figured it out.
I got the hint I needed from
https://github.com/zachriggle/pwntools-glibc-buffering/blob/master/demo.py
It seems that Ubuntu is doing lots of buffering on its own.
When manually making sure that pwnTools uses a pseudoterminal for stdin and stdout it works!
import * from pwn
pty = process.PTY
p = process(stdin=pty, stdout=pty)
You can use the clean function which is more reliable and which can be used for remote connections: https://docs.pwntools.com/en/dev/tubes.html#pwnlib.tubes.tube.tube.clean
For example:
def start():
p = remote("0.0.0.0", 4000)
return p
io = start()
io.send(b"YYYY")
io.clean()
io.send(b"ZZZ")
I'm new to Python and using Pycharm to work with code.
I'm writing a simple program, that read string and then convert it into int.
import sys
print ("Hello word")
data = sys.stdin.read()
tokens = data.split()
for i in range(len(tokens)):
tokens[i] = int(tokens[i])
print (tokens[1])
I ran program, entered three numbers, but that's all
Why, while running the program I can't see the results of print?
It's because the program is still reading from stdin. To read only one line from stdin, you have to use stdin.readline(). If you run a debug process with a breakpoint after the line sys.stdin.read(), you'll see that the program never reaches it. Running your program in Ideone, for example, where it lets you specify stdin before running your app, stdin.read() works fine. Usually it reads until EOF (end of file). So, either use sys.stdin.readline() (built-in input() does just that), or use file input if you want to read multiple lines. You can also refer to this post for more info if you really want to use sys.stdin.read().
You have effectively blocked the program with .read(); its a lot simpler to use input(), like this:
print('Hello World')
data = input()
tokens = map(int, data.split()) # this converts to int
print(tokens[1])
Here's my first simple test program in Python. Without importing the os library the program runs fine... Leading me to believe there's something wrong with my import statement, however this is the only way i ever see them written. Why am I still getting a syntax error?
import os # <-- why does this line give me a syntax error?!?!?! <unicode error> -->
CalibrationData = r'C:/Users/user/Desktop/blah Redesign/Data/attempts at data gathering/CalibrationData.txt'
File = open(CalibrationData, 'w')
File.write('Test')
File.close()
My end goal is to write a simple program that will look through a directory and tabularize data from relevant .ini files within it.
Well, as MDurant pointed out... I pasted in some unprintable character - probably when i entered the URL.
I'm trying to read a huge amount of lines from standard input with python.
more hugefile.txt | python readstdin.py
The problem is that the program freezes as soon as i've read just a single line.
print sys.stdin.read(8)
exit(1)
This prints the first 8 bytes but then i expect it to terminate but it never does. I think it's not really just reading the first bytes but trying to read the whole file into memory.
Same problem with sys.stdin.readline()
What i really want to do is of course to read all the lines but with a buffer so i don't run out of memory.
I'm using python 2.6
This should work efficiently in a modern Python:
import sys
for line in sys.stdin:
# do something...
print line,
You can then run the script like this:
python readstdin.py < hugefile.txt
Back in the day, you had to use xreadlines to get efficient huge line-at-a-time IO -- and the docs now ask that you use for line in file.
Of course, this is of assistance only if you're actually working on the lines one at a time. If you're just reading big binary blobs to pass onto something else, then your other mechanism might be as efficient.
This is a bit of a an odd question but I'll make it out the best I can. I'm in the works on writing a script with the use of proxies, but I ran in to a problem automating part of it, which sucks as it's the last part of everything that I need then I'm done.
Example: Lets say I have a list of 200 or so proxies in this format stored in a .txt file:
110.138.183.60:8080
110.138.20.67:8080
110.138.208.116:8008
110.138.237.80:3128
110.138.248.17:8080
110.138.248.78:80
110.139.182.234:8080
ect ect ect...
First part of this script is I need to randomize them, so just mix them all up in different orders but making sure they all end up on one line each as they are now.
Second part after randomizing them, and then taking the first 99 of the randomized proxies and moving them in to one line in this format, ignoring any proxies after the 99th. (Separated by |, without one at the beginning or end. )
110.138.183.60:8080|110.138.208.116:8008|110.138.237.80:3128|110.138.248.17:8080|110.138.248.78:80|110.139.182.234:8080|110.138.20.67:8080
Third part is I need this new line of proxies to edit and replace a line in a file. The line would currently look something like this:
user_pref("extensions.proxytool.http_proxies", "129.59.26.40:8909|87.106.143.132:3128|85.17.121.205:9090|88.85.125.78:8080|80.82.150.82:8080");
Where you see the proxies in that line, I need to replace them with the new batch of proxies we just created.
End Result looking something like this:
...
user_pref("extensions.proxytool.clear_cookies_on_new_window", true);
user_pref("extensions.proxytool.firstrun", false);
user_pref("extensions.proxytool.http_proxies", "110.138.183.60:8080|110.138.208.116:8008|110.138.237.80:3128|110.138.248.17:8080|110.138.248.78:80|110.139.182.234:8080|110.138.20.67:8080");
user_pref("extensions.proxytool.proxy_type", "http");
user_pref("extensions.proxytool.referer", "default");
...
I wouldn't ask so much if I wasn't desperate, I'm literally on the last hair of my project before completing it. Any help is greatly appreciated! Thanks in advance!
EDIT: Script complete. Credit goes to Zack Bloom for the help! I got a little lazy with how the python script works, instead I have created a default prefs file with an empty proxy line, so outside the python script, a default prefs file is copied over in to my program, and then the python script does it's magic and replaces the line "proxies go here" with the newly compiled list. Thanks again Zack!
from random import sample
with open("C:/Users/USERACCOUNT/test/today.txt") as proxy_file:
proxies = [proxy.strip() for proxy in proxy_file.readlines()]
proxies = sample(proxies, min(len(proxies), 99))
proxy_str = "|".join(proxies)
import fileinput
import sys
def replaceAll(file,searchExp,replaceExp):
for line in fileinput.input(file, inplace=1):
if searchExp in line:
line = line.replace(searchExp,replaceExp)
sys.stdout.write(line)
replaceAll('C:/Users/USERACCOUNT/test/prefs.js','proxiesgohere',proxy_str)
Creating the list is simple enough:
from random import sample
with open("proxy_list.txt") as proxy_file:
proxies = [proxy.strip() for proxy in proxy_file.readlines()]
proxies = sample(proxies, min(len(proxies), 99))
proxy_str = "|".join(proxies)
Then you must use a templating language (there's one in the std lib: http://docs.python.org/library/string.html#template-strings) to create your output file with the string included.