Python how to not print \r and \n - python

I have this code that runs a minecraft server from python and prints everything in the command line. However, at the end of every line it prints "\r\n" and I don't want it to, is there any way to get rid of it?
import subprocess
def run_command(command):
p = subprocess.Popen(command,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
return iter(p.stdout.readline, b'')
for output_line in run_command('java -Xmx2048M -Xms2048M -jar minecraft_server.jar nogui'):
print(output_line)

You can write to stdout directly:
import sys
sys.stdout.write("Hello world!")
sys.stdout.write(" I'm superman :D")
The above code should print on the same line
As requested, it seems like OP wants to print a long string with line breakers embedded, but don't want the line breakers to be effective.
Let's say I have a text file that has two lines
Hey line 1!
I'm line 2.
The following code will print two lines without line breaker, replacing line breakers with spaces:
txt = ''
with open('somename.txt', 'r') as f:
txt = f.read().replace('\r\n', ' ')
txt = txt.replace('\n\r', ' ')
txt = txt.replace('\n', ' ')
txt = txt.replace('\r', ' ')
print txt
That is, it will print
Hey line 1! I'm line 2.
You can also parse the lines, then print each line without line breakers:
for line in f:
sys.stdout.write(line.strip() + ' ')
Hope this is what you want.

Use
print('Minecraft server', end="")
Or
print(output_line.rstrip())

Related

Python search for text over multiple lines

import os
searchquery = 'word'
with open('Y:/Documents/result.txt', 'w') as f:
for filename in os.listdir('Y:/Documents/scripts/script files'):
with open('Y:/Documents/scripts/script files/' + filename) as currentFile:
for line in currentFile:
if searchquery in line:
start = line.find(searchquery)
end = line.find("R")
result = line[start:end]
print result
f.write(result + ' ' +filename[:-4] + '\n')
Now this works well to search for "word" and prints everything after word up until an "R" providing that it is on the same line. However if the "R" is on the line it won't print the stuff before it.
eg:
this should not be printed!
this should also not be printed! "word" = 12345
6789 "R" After this R should not be printed either!
In the case above the 6789 on line 3 will not be printed with my current. However i want it to be. How do i make python keep going over multiple lines until it reaches the "R".
Thanks for any help!
It is normal that it does not print the content on the next line because you are searching for the word on one line. A better solution would be as follows.
import os
searchquery = 'word'
with open('Y:/Documents/result.txt', 'w') as f:
for filename in os.listdir('Y:/Documents/scripts/script files'):
with open('Y:/Documents/scripts/script files/' + filename) as currentFile:
content = ''.join([line for line in currentFile])
start = content.find(searchquery)
end = content.find("R")
result = content[start:end].replace("\n", "")
print result
f.write(result + ' ' +filename[:-4] + '\n')
Please be advised, this will work only for a single occurence. You will need to break it up further to print multiple occurences.

Python match a regex with specified exceptions

I'm using Python Fabric, trying to comment all lines in a file that begin with "#", unless that "#" is followed by 2 specific IP addresses. So if the file contains (without the bullets)
#hi
#IP1
some stuff here
#IP2
then the resulting file should be (also without the bullets)
##hi
#IP1
some stuff here
#IP2
This is what I have so far:
def verify():
output = sudo("/sbin/service syslog status")
#if syslog is running
if 'is running...' in output:
#then set output to the value of the conf file
output = sudo("cat /etc/syslog.conf")
#If pattern is matched
if "#" in output and not "#IP1" and not "#IP2":
#read all the lines in the conf file
sys.stdout = open('/etc/syslog.conf', 'r+').readlines()
#and for every line, comment if it matches pattern
for line in sys.stdout:
if "#" in line and not "#1P1" and not "#IP2":
line = "#" + line
else:
print GOOD
else:
print RSYSLOG
I get that when I say
if "#" in output and not "#IP1" and not "#IP2"
Python is thinking that I am saying "do some thing if there is an # in the file, but ONLY if you also do not have #IP1 and #IP2." What I'm trying to say is "do some thing to any line starting with an #, except the lines #IP1 and #IP2." Also I know there are other errors in my code, but I'm working on just this now.
thanks.
Regex solution:
You can use the following regex to match:
^(?=#(?!(IP1|IP2)))
And replace with #
See DEMO
Code:
re.sub(r'^(?=#(?!(IP1|IP2)))', r'#', myStr)
I would do like,
if not "#IP1" in output or not "#IP2" in output:
if output.startswith("#"):
// stuff here
Check if criteria exists in the glob, and if so, open file, read line-by-line, and use re.sub() to add a # inline to the lines that require it.
import re
ip1 = '1.1.1.1'
ip2 = '2.2.2.2'
fh = open('in.txt', 'r')
f = fh.read()
fh.close()
if re.search(r'(#(?!({0}|{1})))'.format(ip1, ip2), f):
fh = open('in.txt', 'r')
for line in fh:
line = re.sub(r'^(#(?!({0}|{1})))'.format(ip1, ip2), r'#\1', line)
print(line)
Input file:
#1.1.1.1
#this
#2.2.2.2
#3.3.3.3
#
no #
blah
Output:
#1.1.1.1
##this
#2.2.2.2
##3.3.3.3
##
no #
blah

Why the result is not correct using python to know the line numbers of a file

I want to know the line numbers of a certain file
Following is the code
But the result is not correct:The true file line number == Console result number + 1
is the problem in "open().readlines()" ?
if there are contents in the last line, the result is correct
import os
import os.path
absPath = os.curdir
while True:
print '\nplease select the file you want to know the line nums:'
print os.listdir(absPath)
fileName = raw_input()
absFilePath = absPath + '//' + fileName
if os.path.isfile(absFilePath):
count = len(open(absFilePath).readlines())
print 'the ' + fileName + ' file line nums is>>>' + str(count) + '>>>'
else:
print 'Please check the fileName or the input is not a file'
You shouldn't use readlines() here, as it unnecessarily loads the whole file into memory. The following snippet is more memory-friendly:
with open(filename) as f:
line_count = sum(1 for line in f)
I find the reason:
the notepad++ line num(left side) shows 6,
but open().readlines() return list ['aaa\n','bbb\n','ccc\n','\n','\n']
'\n' will add a new line num in editor,but not add a list num
So if the last line is like 'bbb',the script is correct
if the last is like '\n' ,'\n',the line num must add 1

How to find the exact length and matched string in a file using python

I have file contains
"Starting program and
Starting program
Loading molecule...
Initialising variables...
Starting the calculation - this could take a while!
Molecule energy = 2432.6 kcal mol-1
Calculation finished. Bye!"
import sys
import re
search_string = "Starting program"
txtlength=len(search_string)
print "txtlength",txtlength
lines = open( "C:\search.txt", "r" ).readlines()
for line in lines:
if re.search( search_string, line ):
print line,
else :
print "Not found"
I am looking for only 2nd line in the file but ouput coming from this code is 1 line is also displaying
You don't need regex for the example you show:
with open("C:/search.txt") as inp:
for line in inp:
if line.strip() == search_string:
print line

Python: re-formatting multiple lines in text file

I apologize if this post is long, but I am trying to be as detailed as possible. I have done a considerable amount of research on the topic, and would consider myself an "intermediate" skilled programmer.
My problem: I have a text file with multiple lines of data. I would like to remove certain parts of each line in an effort to get rid of some irrelevant information, and then save the file with the newly formatted lines.
Here is an example of what I am trying to accomplish. The original line is something like:
access-list inbound_outside1 line 165 extended permit tcp any host 209.143.156.200 eq www (hitcnt=10086645) 0x3eb90594
I am trying to have the code read the text file, and output:
permit tcp any 209.143.156.200 www
The following code works, but only if there is a single line in the text file:
input_file = open("ConfigInput.txt", "r")
output_file = open("ConfigOutput.txt", "w")
for line in input_file:
line = line.split("extended ", 1)[1]
line = line.split("(", 1)[0]
line = line.replace(" host", "")
line = line.replace(" eq", "")
output_file.write(line)
output_file.close()
input_file.close()
However, when I attempt to run this with a full file of multiple lines of data, I receive an error:
File "C:\Python27\asaReader", line 5, in <module>
line = line.split("extended ", 1)[1]
IndexError: list index out of range
I suspect that it is not moving onto the next line of data in the text file, and therefore there isn't anything in [1] of the previous string. I would appreciate any help I can get on this.
Some possible causes:
You have blank lines in your file (blank lines obviously won't contain the word extended)
You have lines that aren't blank, but don't contain the word extended
You could try printing your lines individually to see where the problem occurs:
for line in input_file:
print("Got line: %s" % (line))
line = line.split("extended ", 1)[1]
Oh, and it's possible that the last line is blank and it's failing on that. It would be easy enough to miss.
Print something out when you hit a line that can't be processed
for line in input_file:
try:
line = line.split("extended ", 1)[1]
line = line.split("(", 1)[0]
line = line.replace(" host", "")
line = line.replace(" eq", "")
output_file.write(line)
except Exception, e:
print "Choked on this line: %r"%line
print e
An alternate approach would be to cache all the lines (assuming the file is not humongous.)
>>> with open('/tmp/ConfigInput.txt', 'rU') as f:
... lines = f.readlines()
...
...
>>> lines
['access-list inbound_outside1 line 165 extended permit tcp any host 209.143.156.200 eq www (hitcnt=10086645) 0x3eb90594\n']
>>> lines = [re.sub('(^.*extended |\(.*$)', '', line) for line in lines]
>>> lines
['permit tcp any host 209.143.156.200 eq www \n']
>>> with open('/tmp/ConfigOutput.txt', 'w') as f:
... f.writelines(lines)
...
...
>>>

Categories

Resources