Can't break a line with string in optparse - python

I am trying to break a line with \n with optparse. Example: line1 \n line2
But when I type \n it doesn't break it just prints it as line1 \n line2, instead of doing a break. Here is my code:
import optparse
import sys
def main():
progparse = optparse.OptionParser("usage " + "--message <text here>")
progparse.add_option("--message", dest="msg_txt", type="string", help="Type the message you want to send")
msg_txt = ""
if (options.msg_txt == None):
print(progparse.usage)
sys.exit()
print(options.msg_txt)
if __name__ == '__main__':
main()
If I just do a simple print statment with \n then it will break the line, why doesn't it do it when using optparse?

option1, use real new line in your input:
$ python3 test.py --message "line1
> line2
> line3"
line1
line2
line3
option2, eval \n as real new line with ast.literal_eval:
print(ast.literal_eval('"' + options.msg_txt + '"'))
note this may raise an exception for ill-formed input.

Related

How do I handle the ',' in the sys.argv __name__ statement below

This is a little terminal journal app I am working on.
Intended functionality: type in terminal python3 journal.py whatever note I want to keep, with commas included. The entry 'whatever note I want to keep, with commas included' gets stored in a csv in a single cell.
Actual functionality: the note 'whatever note I want to keep, with commas included' is split into multiple cells on the ','. This problem was solved in the multi_stuff function but the same technique isn't working in the sys.argv[1:] in the name portion.
any thoughts?
import csv
import sys
import re
import datetime
def record(stuff):
with open('journal.csv', 'a') as f:
f.write(str(datetime.datetime.now())+','+stuff+'\n')
def multi_line():
while True:
multi_stuff = input('Type "Q" to quit. Otherwise, talk to me -> ').lower()
if ',' in multi_stuff:
multi_stuff = multi_stuff.replace(',', '","')
if multi_stuff == 'q':
break
with open('journal.csv', 'a') as f:
f.write(str(datetime.datetime.now())+','+multi_stuff+'\n')
def search():
keyword = input('search term -> ').lower()
regex = r"\b(?=\w)" + re.escape(keyword) + r"\b(?!\w)"
with open('journal.csv', 'r') as csv:
for line in csv:
if re.search(regex, line):
print(line)
if __name__ == '__main__':
if sys.argv[1].lower() == '-s':
search()
elif sys.argv[1].lower() == '-m':
multi_line()
else:
arg = sys.argv[1:]
if ',' in arg:
arg = arg.replace(',', '","')
record(' '.join(arg))
else:
record(' '.join(arg))

Python how to not print \r and \n

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())

Why are strings from sys.stdin different from hardcoded strings in my script?

Why does the following print "False"?
test.py:
import sys
if __name__ == "__main__":
for text in sys.stdin:
text_in_script = 'test'
print(text == text_in_script)
Command line:
echo test | py -3 test.py
Because sys.stdin texts come with a new line character. It is more obvious when test.py is this:
import sys
if __name__ == "__main__":
for text in sys.stdin:
text_in_script = 'test'
print("Input: {}".format(text))
print("Script: {}".format(text_in_script))
print(text == text_in_script)
The solution would be to strip the new line character. The following will return "True":
import sys
if __name__ == "__main__":
for text in sys.stdin:
text_in_script = 'test'
# warning: rstrip() removes all whitespace; see rstrip() docs for alternatives
print(text.rstrip() == text_in_script)

Why is target.write ignoring my %r formatting?

I'm trying to write a program similar to this guy's Learn Python the Hard Way program, near the top of the page.
http://learnpythonthehardway.org/book/ex16.html
This is my version below. But it tells me off for using "%r" at the end, why does it do that? I thought that's what you're meant to do in parenthesis.
# -- coding: utf-8 --
from sys import argv
script, filename = argv
print "Would you like file %r to be overwritten?" % filename
print "Press RETURN if you do, and CTRL-C otherwise."
raw_input('> ')
print "Opening the file ..."
target = open(filename, 'w')
target.truncate()
print "Now type three lines to replace the contents of %r" % filename
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
print "The lines below have now overwritten the previous contests."
target.write("%r\n%r\n%r") % (line1, line2, line3)
target.close()
You need to place the % operator directly after the format string. Take the parenthesis here:
target.write("%r\n%r\n%r") % (line1, line2, line3)
# --^
And move it to the end of the line:
target.write("%r\n%r\n%r" % (line1, line2, line3))
# --^
Also, I would like to mention that performing string formatting operations with % is frowned upon these days. The modern approach is to use str.format:
target.write("{0!r}\n{1!r}\n{2!r}".format(line1, line2, line3))

KeyboardInterrupt close failed in file object destructor: sys.excepthook is missing lost sys.stderr

#!/usr/bin/env python
import sys, re
def find_position(line):
pun = ""
if re.search(r"[.?!]+", line):
pun = re.search(r"[.?!]+", line).group()
pos = line.find(pun)
pos = pos+len(pun)-1
return pos
def sentence_splitter(filename):
f = open(filename, "r")
for line in f:
line = line.strip()
print line + "\n"
while line:
pos = find_position(line)
line2 = line[ : pos+1].split(" ")
length = len(line2)
last_word = line2[length -1]
try:
if re.search(r"[A-Z]+.*", last_word) or line[pos+1] != " " or line[pos+2].islower() :
print line[:pos+1],
line = line[pos+1:]
else:
print line[ : pos+1]
line = line[pos+1 :]
except :
print " error here!!"
f.close()
return " bye bye"
if __name__=="__main__":
print sentence_splitter(sys.argv[1])
on executing it
python sentence_splitter6.py README | more
error occur
KeyboardInterrupt
close failed in file object destructor:
sys.excepthook is missing
lost sys.stderr
also i have to press clr+c
it is not closed by its own
tried stuffs on this
How to handle a file destructor throwing an exception?
How to silence "sys.excepthook is missing" error?
links also but not saisfied please help
First of all, your problem is here:
while line:
pos = find_position(line)
line2 = line[:pos + 1].split(" ")
length = len(line2)
last_word = line2[length - 1]
line is not modified, so if its true once, it's always true, the while have no way to end.
Then, the KeyboardInterrupt does not comes from your execution but from you pressing C-c, halting your program.
Also you should respect the PEP8 while writing python code, also you can check it with flakes8 and/or pylint.
Here is PEP8 compliant version (still have the infinite loop):
#!/usr/bin/env python3
import sys, re
def find_position(line):
pun = ""
if re.search(r"[.?!]+", line):
pun = re.search(r"[.?!]+", line).group()
pos = line.find(pun)
pos = pos+len(pun)-1
return pos
def sentence_splitter(filename):
with open(filename, "r") as infile:
for line in infile:
line = line.strip()
print(line + "\n")
while line:
pos = find_position(line)
line2 = line[:pos + 1].split(" ")
length = len(line2)
last_word = line2[length - 1]
if ((re.search(r"[A-Z]+.*", last_word) or
line[pos+1] != " " or
line[pos+2].islower())):
print(line[:pos+1], end='')
line = line[pos+1:]
else:
print(line[:pos + 1])
line = line[pos + 1:]
return " bye bye"
if __name__ == "__main__":
print(sentence_splitter(sys.argv[1]))
Finally, you should comment your code so everyone including you can understand what you're doing, like:
def find_position(line):
"""Finds the position of a pun in the line.
"""
Also find_pun_position is probably a better name...

Categories

Resources