Show lines of a file where an argument is found - python

I want to make a simple script where the user enters an argument and all the lines where the argument exists appear on the screen.
This script will be used to make the search in one of my log files (which is very long and constantly updated) easier.
I had thought of using grep for this, then I finally got the idea to change to glob which is better since we can work with several arguments.
But the code doesn't seem to work. When I try anything, nothing is displayed. I am a beginner in python and I can't see what exactly is wrong with my code.
In case the code works, it should show all lines in the log file where the given argument is present. But this is not the case.
import re
import sys
import glob
import os
if len(sys.argv) != 2:
print("Syntaxe: %s <UserID or IP Address>" % sys.argv[0].split('/')[-1])
sys.exit(1)
file = os.path.join("/applis/tacacs/log/tacacs.log")
for arg in sys.argv[2:]:
for file in glob.iglob(arg):
for line in open(file, 'r'):
if re.search(sys.argv[1], line):
print line,
Could someone please tell me what is wrong with my code? Thanks in advance.

Related

Write to a notepad typing

Can anyone help me fix this code? Trying to get it to write to a notepad but it just opens the file then stops. Any help is appreciated.
(I also want it to be like its typing instead of just c&p)
import subprocess as sp
sp.Popen(['notepad', "helloworld.txt"])
f = open('helloworld.txt','w')
import sys
from time import sleep
words = "hi"
for char in words:
sleep(0.5)
f.write(char)
sys.stdout.flush()
Let's assume that, when you request that notepad be opened in the second line of your code the file helloworld.txt does not exist.
I wrote request that notepad be opened because this takes time. Meanwhile, the rest of your code is proceeding. If you were to omit the sleep and the import statements then it would execute in a heartbeat, well ahead of the time it takes to start up notepad.
Assuming that you had closed the file helloworld.txt it would be available to notepad by the time it opened!
However, we usually don't depend on uncertain timing. (Trust me.)
We would create the file, then open it with notepad, more or less like this.
f = open('helloworld.txt','w')
words = "hi"
for char in words:
f.write(char)
f.close()
import subprocess as sp
sp.Popen(['notepad', "helloworld.txt"])
I must add that this is not the same as writing directly into notepad itself. If you're asking about that then please see pywinauto or one of the other libraries mentioned on that page.

Why do I get a SyntaxError <unicode error> on my import statement? Should this not be simple?

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.

How do I print the output onto a txt file: Mac

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.

Reading output from os.popen4 before writing writing stdin

I have a script which executes some command using os.popen4. Problem is some time command being executed will require user input ("y" or "n"). I am reading stdout/stderr and printing it, but it seems question from command doesn't got printed and it hangs. To make it work, i had to write "n" to stdin blindly. Can some one please guide on how to handle it?
Code not working:
(f_p_stdin, f_p_stdout_stderr) = os.popen4(cmd_exec,"t")
cmd_out = f_p_stdout_stderr.readlines()
print cmd_out
f_p_stdin.write("n")
f_p_stdin.close()
f_p_stdout_stderr.close()
Working Code:
(f_p_stdin, f_p_stdout_stderr) = os.popen4(cmd_exec,"t")
cmd_out = f_p_stdout_stderr.readlines()
f_p_stdin.write("n")
f_p_stdin.close()
print cmd_out
f_p_stdout_stderr.close()
NOTE : I am aware that it is depreciated and subprocess module is used, but right now i don't know on how to use it. So i'll appreciate if some one will help me to handle it using os.popen4. I want to capture the question and handle the input from user and execute it.
readlines() : returns a list containing all the lines of data in the file. If reading from a process like in this case, there is a good chance it does not send a newline and/or flush the output. You should read characters from the input and process that to see if the question was posed.
It would help to know what cmd_exec looks like, so others can try and emulate what you tried.
Update:
I wrote a uncheckout command in Python:
#! /usr/bin/env python
# coding: utf-8
import sys
print 'Uncheckout of {} is irreversible'.format(sys.argv[1])
print 'Do you want to proceed? [y/N]',
sys.stdout.flush()
x = raw_input()
if x == 'y':
print sys.argv[1], "no longer checked out"
else:
print sys.argv[1], "still checked out"
I put the prompt string on purpose not as argument to raw_input, to be able to do the flush() explicitly.
Neither of your code snippets work with that (assuming cmd_exec to be ['./uncheckout', 'abc.txt'] or './uncheckout abc.txt', popen4() uses the shell in the latter case to start the program).
Only when I move the readlines() until after the write() and close() will the command continue.
That makes sense to me as the close() flushes the output. You are writing in text mode and that buffers normally until end-of-line, which is not in your .write('n').
To be able to check what the prompt is and test and react on that., the following works with the above uncheckout:
#! /usr/bin/env python
# coding: utf-8
import os
import sys
cmd_exec = ['./uncheckout', 'abc.txt']
(f_p_stdin, f_p_stdout_stderr) = os.popen4(cmd_exec,"t")
line = ''
while True:
x = f_p_stdout_stderr.read(1)
if not x:
break
sys.stdout.write(x)
sys.stdout.flush()
if x == '\n':
line = ''
else:
line += x
if line.endswith('[y/N]'):
f_p_stdin.write("n\n")
f_p_stdin.flush()
sys.stdout.write('\n')
Maybe you can work backwards from that to make something that works for you. Make sure to keep flushes at appropriate places.

I don't even know what infile > outfile means. How am I supposed to use it?

I don't know how to use Python, and I'm trying to use a script on a document. I have no idea how to tell it do this!
If I just run the script, this is the message I get:
Use: C:\Python27\hun2html.py infile > outfile
Traceback (most recent call last):
File "C:\Python27\hun2html.py", line 75, in <module>
sys.exit(1)
SystemExit: 1
I'm not sure what info is relevant to anyone who knows about this stuff, but this is the most relevant part of the code, I believe:
if __name__ == '__main__':
import sys
if not sys.argv[1:]:
print "Use: %s infile > outfile" % sys.argv[0]
sys.exit(1)
contents = open(sys.argv[1]).read()
print hun2html(contents)
It's supposed to change the formatting in a document. If anyone can make sense of this stupid question, I would really appreciate some help!
It means that you should write the path to the file you want to use for input where infile is and the path to the file you want to store the output where outfile is. For example,
C:\Python27\hun2html.py C:\input.txt > C:\output.txt
Note that the input file is being passed as a parameter (accessed in the code by sys.argv[1] ) and the output is being piped, meaning that the Python prints it to standard output, but because you put the > character it will be redirected to the file you indicate. If you left off the > outfile you would see the output displayed on your terminal.
You give it the input file as the first parameter and redirect the standard output to the file where you want to write the result. For example:
C:\Python27\hun2html.py myfile.hun >myfile.html
The > symbols tells it that whatever gets printed to the standard output will get written to a file, instead of the console. There is also < which will read a file to the standard input.
Suppose you have a document named input.doc. If you run hun2html.py input.doc it will display the output to that terminal.
However, since you want to have the output in another file you'll have to redirect the output to a file. That's where > outfile comes into play. If you want to save the output in output.html, you'll have to do this:
hun2html.py input.doc > output.html
Hope it helps.

Categories