Why i cant get the process that exist on print? - python-2.7

import os
import time
os.system('WMIC /OUTPUT:C:\Users\PRO\Desktop\ProcessList.txt PROCESS get Caption')
with open('C:\Users\PRO\Desktop\ProcessList.txt', 'r') as f:
if str('System') in f:
print "Yes"
else:
print "No"

I have tried your code, and it was needed some little modification. I did that, but didn't get desirable result. It write successfully in a mentioned file. So, I though it would be better if I print out each line in my python IDLE. I got such weird result.
At first, it looked fine, when open in any text editor. But later, after finding this weird space between each character, I opened this file in Sublime editor, run over there, then found something look like this
After googling a little bit, I found that this is a NUL terminator used to teminate the string in C\C++. Maybe someone with more knowledge about this can explain it better.
I have no idea, how and why it is adding it after every character. But if you remove that and run again the code, you'll get the desirable result.
Kindly find the below updated code:
import os
import time
os.system('WMIC /OUTPUT:C:\Users\sohan.tirpude\Documents\LogInLog.txt PROCESS get Caption')
searchfile = open("C:\Users\sohan.tirpude\Documents\LogInLog.txt", "r")
for line in searchfile:
line = line.replace('\0', '')
#print line
if 'System' in line:
print "Yes"
break
else:
print "No"
Kindly give it a try.

Related

Python 2.7.15 adds a new line in Windows to the end but not on Linux. How do I fix this?

This is not a typical "how do I strip a new line or spaces" question...
I am new to python in general. But I am aware of
print ("test", end="")
print ("test", end="")
for Python 3 and
print "test",
print "test",
for Python 2
Python 3 implementation will print correctly on both Linux and Windows machines; however the Python 2 implementation will add an extra line at the end of the execution on Windows based machines (but not Linux, there it prints correctly). Is there any way to get rid of this new line?
I have searched around and I cant seem to find anyone talking about this particular issue. Here is a screenshot for demonstration:
So, in accordance with the print documentation
Standard output is defined as the file object named stdout
And we probably assume that python I\O are system dependent, so that's how we could try to guess the explanation of this situation, even thought print documentation states:
A '\n' character is written at the end, unless the print statement
ends with a comma.
OR The reason is that Windows & Linux threat print statement differently (since print is a statement in Python 2, and a function call in Python 3).
Back to the question, how to get rid of this line:
I used future statement for print function:
from __future__ import print_function
print('test', end=' ')
print('test', end='')
If I find any reasonable explanation, I will update the answer (should be somewhere !).
After speaking to a few people about this and doing some research. It appears the most straightforward way around this issue is to directly use:
sys.stdout.write()
instead of print. You can then format your output similar to the way C/C++ and Java work.

Python Search String One Liner

I'm trying to use Python a little more and I know this isn't the best use case for it but it's bothering me on why I can't get it to work.
I'm currently using Python 2.7.6 and I want to cat a file and then pull specific strings out of it based on regex. The below code works fine for what I want, but only looks at the first line.
cat /tmp/blah.txt | python -c "import re,sys; m = re.search('Host: (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}).*OS:(.*) Seq:', sys.stdin.read()); print m.group(1), m.group(2)"
So I assumed I could just use a for loop or fileinput to read the entire file and then put the rest of my code in there but I keep on getting errors with the for loop.
cat /tmp/blah.txt | python -c "import sys; for line in sys.stdin: print line" File "<string>", line 1
import sys; for line in sys.stdin: print line
^
SyntaxError: invalid syntax
I've tried a few variations of this but can't get it to work. It always says invalid syntax at the for portion. I know it has to be something very stupid/obvious I'm doing but any help would be appreciated.
If I created a program called arg.py and put the code below in it and call Python via cat, it works fine. It's just the one liner portion that isn't working.
import sys
for line in sys.stdin:
print line
Unfortunately, constructs that introduce indentation in python like if, for among others are not allowed to be preceded by other statements.
Even in your arg.py file try the following:
import sys; for line in sys.stdin: print line
You will discover that the syntax is also invalid which results to the same error.
So, to answer your question, your problem is not the fact that you ran the program in the terminal but the problem is in python syntax itself. It does not support such syntax
Check out a related question

How to paste multiple lines to an ipdb shell in python?

I am working with python and ipdb debugger.
Let's say is set some breaking point in some line in a python file.
Now, after running the python file, the program stops at the breakpoint.
I want to be able to paste multiple lines to the ipdb shell.
Now i get an error, if trying to paste mutiple lines.
How can i paste mutiple lines?
Thanks.
As far as I know, you cannot simply paste them. You have to use ; to indicate indentation. For example:
for i in range(10): print i; print("hello")
would be equivalent to
for i in range(10):
print(i)
print("hello")
If you want the hello out of the loop, then you need to use ;; instead:
for i in range(10): print i;; print("hello")

Pygments syntax highlighter in python tkinter text widget

I have been trying to incorporate syntax highlighting with the tkinter text widget. However, using the code found on this post, I cannot get it to work. There are no errors, but the text is not highlighted and a line is skipped after each character. If there is a better way to incorporate syntax highlighting with the tkinter text widget, I would be happy to hear it. Here is the smallest code I could find that replicates the issue:
import Tkinter
import ScrolledText
from pygments import lex
from pygments.lexers import PythonLexer
root = Tkinter.Tk(className=" How do I put an end to this behavior?")
textPad = ScrolledText.ScrolledText(root, width=100, height=80)
textPad.tag_configure("Token.Comment", foreground="#b21111")
code = textPad.get("1.0", "end-1c")
# Parse the code and insert into the widget
def syn(event=None):
for token, content in lex(code, PythonLexer()):
textPad.insert("end", content, str(token))
textPad.pack()
root.bind("<Key>", syn)
root.mainloop()
So far, I have not found a solution to this problem (otherwise I would not be posting here). Any help regarding syntax highlighting a tkinter text widget would be appreciated.
Note: This is on python 2.7 with Windows 7.
The code in the question you linked to was designed more for highlighting already existing text, whereas it looks like you're trying to highlight it as you type.
I can give some suggestions to get you started, though I've never done this and don't know what the most efficient solution is. The solution in this answer is only a starting point, there's no guarantee it is actually suited to your problem.
The short synopis is this: don't set up a binding that inserts anything. Instead, just highlight what was inserted by the default bindings.
To do this, the first step is to bind on <KeyRelease> rather than <Key>. The difference is that <KeyRelease> will happen after a character has been inserted whereas <Key> happens before a character is inserted.
Second, you need to get tokens from the lexer, and apply tags to the text for each token. To do that you need to keep track where in the document the lexer is, and then use the length of the token to determine the end of the token.
In the following solution I create a mark ("range_start") to designate the current location in the file where the pygments lexer is, and then compute the mark "range_end" based on the start, and the length of the token returned by pygments. I don't know how robust this is in the face of multi-byte characters. For now, lets assume single byte characters.
def syn(event=None):
textPad.mark_set("range_start", "1.0")
data = textPad.get("1.0", "end-1c")
for token, content in lex(data, PythonLexer()):
textPad.mark_set("range_end", "range_start + %dc" % len(content))
textPad.tag_add(str(token), "range_start", "range_end")
textPad.mark_set("range_start", "range_end")
This is crazy inefficient since it re-applies the highlighting to the whole document on every keypress. There are ways to minimize that, such as only highlighting after each word, or when the GUI goes idle, or some other sort of trigger.
To highlight certain words you can do this :
textarea.tag_remove("tagname","1.0",tkinter.END)
first = "1.0"
while(True):
first = textarea.search("word_you_are_looking_for", first, nocase=False, stopindex=tkinter.END)
if not first:
break
last = first+"+"+str(len("word_you_are_looking_for"))+"c"
textarea.tag_add("tagname", first, last)
first = last
textarea.tag_config("tagname", foreground="#00FF00")

Python: Iterate through an html file

I'm trying to iterate through an html file from the internet.
target = br.response().read()
for row in target:
if "[some text]" in row:
print next(target)
The problem is this loop iterates over each character in the html file, so it'll never find a match. How do I get it to iterate through each row instead?
I've tried target = target.splitlines() , but that really messes up the file.
What you basically want to achieve is the following (reading from a file, as your header suggests):
#!/usr/bin/env python
import sys
with open("test.txt") as file:
for line in file:
if "got" in line:
print "found: {0}".format(line)
You want to open your file ("test.txt").
You read each line (for .. in)
and look if the line contains a string, where in comes in nice:)
If you are interested in the line number:
for index, line in enumerate(file):
But beware the index starts with 0, so the current line number is index+1
Analog, if you want to read from a String as a file, take a look at StringIO.
Take a look at the page source for the file you're viewing, because that's what you're getting back as a response. I have a feeling the response you're getting doesn't actually have new lines where you want it to. For pages like http://docs.python.org/ where the source is readable your splitline() method works great, but for sites where the source essentially has no line breaks, like Google's homepage, it's a lot closer to the problems you're experiencing.
Depending on what you are trying to achieve, your best bet might be to use an html/xml parsing library like lxml. Otherwise using re is probably a pretty safe approach. Both are a lot better than trying to guess where the line breaks should be.