Iv'e read various guides on Multi-Line Statements but cannot find a guide that has comments, variables, text and text that requires splitting over multiple lines.
I'm struggling to split the below code:
ex = 25
cmd = 'raspistill -o ' + filename + ' -t 1000 -ex ' + ex
onto a multi line with comments, like this:
cmd = 'raspistill -o ' + filename + \ # explain line 1
' -t 1000' \ # explain line 2
'-ex ' + ex # explain line 3
Is this the best way to split code over multiple lines?
You can use parentheses instead of backslashes to do line continuations:
a = ( "aaa" + # foo
"bbb" + # bar
"ccc" # baz
)
Basically when you have an expression in any kind of brackets, python will not end statements at the end of line, but will first wait until it finds the corresponding closing bracket.
I find it more readable and idiomatic than the backslashes.
I'm not sure what language you're using, but this statement is probably not being parsed the way you think:
cmd = 'raspistill -o ' + filename + \ # explain line 1
' -t 1000' \ # explain line 2
'-ex ' + ex # explain line 3
In Python, you'd get the error:
SyntaxError: unexpected character after line continuation character
The problem is that the line continuation character (backslash \) isn't escaping the newline, it's only escaping the space after it. That's because the newline doesn't follow the backslash. It doesn't come until much later, after your comment. So you still have 3 separate lines here.
Get rid of the extra comments and put them in the front, for example:
# explain lines 1, 2, and 3
#
cmd = 'raspistill -o ' + filename + \
' -t 1000' \
'-ex ' + ex
Related
I have a python file, which has lots of double parentheses like this, which i would like to replace with single parenthesis.
Sometimes the print goes on for 2 lines or more.
print(('>> # some text some text some text and '
+ 'some more text'))
print(('>> # some text some text some text and '
+ 'some more text'))
print(('>> # some text some text some text and '
+ 'some more text'))
print(('>> # some text some text some text and '
+ 'some more text'))
print((something))
print((something))
print((something))
print((something))
print((something))
print((something))
I have tried a lot different ways to approach this. I think the easiest would be with sed. I have something like this:
grep -rl 'print((' test.txt | xargs sed -i "N;s/print((\(.*\)))/print(\1)/g"
The output looks like this:
print('>> # some text some text some text and '
+ 'some more text')
print('>> # some text some text some text and '
+ 'some more text')
print(('>> # some text some text some text and '
+ 'some more text'))
print(('>> # some text some text some text and '
+ 'some more text'))
print(something)
print(something)
print(something)
print(something)
print(something)
print(something)
Now with some lines it works but with some it doesn't, i think it is because of the N; but i need this in case it is multiple lines long..
What could i do to improve this pattern?
to avoid issues due to input file names, use grep -rlZ 'regex' | xargs -0 <command ...>
if content within parenthesis doesn't have )), then you can use this
grep -rlZ 'print((' | xargs -0 perl -i -0777 -pe 's/print\(\((.*?)\)\)/print($1)/sg'
-0777 to slurp entire file content as a single string, so this solution not fit for large files that cannot fit memory requirements
.*? is non-greedy matching
s modifier allows to match \n as well for .
When using -i option, you can specify a backup suffix (ex: -i.bkp) or prefix (ex: -i'bkp.*') or even a backup directory (ex: -i'bkp_dir/*') - these help in preserving the original copy for further use
I am very new to Python. I am constructing a string that is nothing but a path to the network location as follows. But it outputs the error: "Python unexpected character after line continuation character". Please help. I saw this post but I am not sure if it applies to my scenario:
syntaxerror: "unexpected character after line continuation character in python" math
s_path_publish_folder = r"\\" + s_host + "\" + s_publish_folder "\" + s_release_name
One of your \ backslashes escapes the " double quote following it. The rest of the string then ends just before the next \ backslash, and that second backslash is seen as a line-continuation character. Because there's another " right after that you get your error:
s_path_publish_folder = r"\\" + s_host + "\" + s_publish_folder "\" + s_release_name
# ^^ not end of string ||
# ^--- actual string ---^||
# line continuation /|
# extra character /
You need to double those backslashes:
s_path_publish_folder = r"\\" + s_host + "\\" + s_publish_folder "\\" + s_release_name
Better yet, use the os.path module here; for example, you could use os.path.join():
s_path_publish_folder = r"\\" + os.path.join(s_host, s_publish_folder, s_release_name)
or you could use string templating:
s_path_publish_folder = r"\\{}\{}\{}".format(s_host, s_publish_folder, s_release_name)
I need to use a dictionary database, but most of it is some alphanumeric useless stuff, and the interesting fields are either non alphanumeric (such as chinese characters) or inside some brackets. I searched a lot, learned about a lot of tools like sed, awk, grep, ect I even thought about creating a Python script to sort it out, but I never managed to find of a solution.
A line of the database looks like this:
助 L1782 DN1921 K407 O431 DO346 MN2313 MP2.0376 E314 IN623 DA633 DS248 DF367 DH330 DT284 DC248 DJ826 DG211 DM1800 P1-5-2 I2g5.1 Q7412.7 DR3945 Yzhu4 Wjo ジョ たす.ける たす.かる す.ける すけ {help} {rescue} {assist}
I need it to be like this :
助 ジョ たす.ける たす.かる す.ける すけ {help} {rescue} {assist}
Ho can I do this using any of the tools mentioned above?
Here is a Python solution if you would still like one:
import re
alpha_brack = re.compile(r"([a-zA-Z0-9.\-]+)|({.*?})")
my_string = """
助 L1782 DN1921 K407 O431 DO346 MN2313 MP2.0376 E314 IN623 DA633 DS248 DF367
DH330 DT284 DC248 DJ826 DG211 DM1800 P1-5-2 I2g5.1 Q7412.7 DR3945 Yzhu4
Wjo ジョ たす.ける たす.かる す.ける すけ {help} {rescue} {assist}"""
match = alpha_brack.findall(my_string)
new_string = my_string
for g0, _ in match: # only care about first group!
new_string = new_string.replace(g0,'',1) # replace only first occurence!
final = re.sub(r'\s{2,}',' ', new_string) # finally, clean up whitespace
print(final)
My results:
'助ジョ たすける たすかる すける すけ {help} {rescue} {assist}'
Personally, given your example line, I'd sed out all alphanumeric characters that start and end with a space:
sed -i 's/ [a-zA-Z0-9 .-]+ / /g' should be close to what you need. You may have to add more special characters if the text you're wiping out contains other things. This is an in-place substitution for a single space (essentially deleting).
No linux box handy to verify this one... it may require a little massaging.
Also worth mentioning, this will not work if the brackets can contain two spaces: {test results found} as it'll blow away the results
Using perl:
perl -ne '
m/(.*?)({.*)/; # Split based on '{'
my $a=$1; my $b=$2;
$a =~ s/[[:alnum:]-.]//g; #Remove alphabets, numbers, '.', '-' (add more characters as you need.)
$a =~ s/ +/ /g; # Compress spaces.
print "$a $b\n"; #Print 2 parts and a newline
' dbfile.txt
Explanation in the inline comments.
Similar logic with sed:
sed '
h; #Save line in hold space.
s/{.*//; # Remove 2nd part
s/[a-zA-Z0-9.-]//g; # Remove all alphabets, numbers, . & -
s/ */ /g; # Compress spaces
x; #Save updated 1st part in hold space, take back the complete line in pattern space
s/[^{]*{/{/; #Remove first part
x; #Swap hold & pattern space again.
G; # Append 2nd part to first part separated by newline
s/\n//; # Remove newline.
' dbfile.txt
Using shell script (Bash):
#!/bin/bash
string="助 L1782 DN1921 K407 O431 DO346 MN2313 MP2.0376 E314 IN623 DA633 DS248 DF367 DH330 DT284 DC248 DJ826 DG211 DM1800 P1-5-2 I2g5.1 Q7412.7 DR3945 Yzhu4 Wjo ジョ たす.ける たす.かる す.ける すけ {help} {rescue} {assist}"
echo "" > tmpfield
for field in $string
do
if [ "${field:0:1}" != "{" ];then #
echo $field|sed "s/[a-zA-Z0-9 .-]/ /g" >> tmpfield
else
echo $field >> tmpfield
fi
done
#convert rows to one column
cat tmpfield | awk 'NF'|awk 'BEGIN { ORS = " " } { print }'
My output:
nampt#nampt-desktop:/mnt$ bash 1.bash
助 ジョ たす ける たす かる す ける すけ {help} {rescue} {assist}
I ran shell commands in python, logged their outputs into files and finally showed on a web page. however the color style chars of command outputs were also logged. is there a way to filter out the color style chars or display them correctly on web pages? Many thanks!
Output log:
" 22200K .......\u001b[0m\u001b[91m... .......... ...\u001b[0m\u001b[91m.\u001b[0m\u001b[91m...... .........\u001b[0m\u001b[91m.\u001b[0m\u001b[91m \u001b[0m\u001b[91m.\u001b[0m\u001b[91m.\u001b[0m\u001b[91m.\u001b[0m\u001b[91m.\u001b[0m\u001b[91m...... 50% 28.6K 12m55s"
the real text:
[INFO][88] 22250K .......... .......... .......... .......... .......... 50% 35.8K 12m53s
In the unlikely case when you have xterm256 color codes as well, this will filter both 'normal' ansi and xterm256 ansi codes:
import re
print(re.sub(r'\x1b(\[.*?[#-~]|\].*?(\x07|\x1b\\))', '', a))
or in a slightly less obfuscated and more readable form:
'(' + CSI + '.*?' + CMD + '|' + OSC + '.*?' + '(' + ST + '|' + BEL + ')' + ')'
Complete code with tests:
import re
tests = [
u"22200K .......\u001b[0m\u001b[91m... .......... ...\u001b[0m\u001b[91m.\u001b[0m\u001b[91m...... .........\u001b[0m\u001b[91m.\u001b[0m\u001b[91m \u001b[0m\u001b[91m.\u001b[0m\u001b[91m.\u001b[0m\u001b[91m.\u001b[0m\u001b[91m.\u001b[0m\u001b[91m...... 50% 28.6K 12m55s",
u"=\u001b[m=",
u"-\u001b]23\u0007-",
]
def trim_ansi(a):
ESC = r'\x1b'
CSI = ESC + r'\['
OSC = ESC + r'\]'
CMD = '[#-~]'
ST = ESC + r'\\'
BEL = r'\x07'
pattern = '(' + CSI + '.*?' + CMD + '|' + OSC + '.*?' + '(' + ST + '|' + BEL + ')' + ')'
return re.sub(pattern, '', a)
for t in tests:
print(trim_ansi(t))
As a one-liner:
ls --color | python -c 'import re, sys; sys.stdout.write(re.sub(r"\x1b(\[.*?[#-~]|\].*?(\x07|\x1b\\))", "", sys.stdin.read()))'
This should work in most cases:
import re
print(re.sub(u'\u001b\[.*?[#-~]', '', a))
Update
Escape sequences start with the character ESC (ASCII decimal 27/hex 0x1B/octal 033). For two character sequences, the second character is in the range ASCII 64–95 (# to _).
However, most of the sequences are more than two characters, and start with the characters ESC and [ (left bracket). This sequence is called CSI for Control Sequence Introducer (or Control Sequence Initiator). The final character of these sequences is in the range ASCII 64–126 (# to ~).
(http://en.wikipedia.org/wiki/ANSI_escape_code)
Update2
With the following 'a.py':
import sys, re
for line in sys.stdin:
sys.stdout.write(re.sub(u'\u001b\[.*?[#-~]', '', line))
this works smoothly for me:
ls --color | python a.py
This python recipe transforms ansi codes to html:
http://code.activestate.com/recipes/577349-convert-a-transcript-with-ansi-escape-sequences-to/
You can simply pipe the output through strings to remove any non-printable characters:
./some-script | strings
I am having problems with this Python program I am creating to do maths, working out and so solutions but I'm getting the syntaxerror: "unexpected character after line continuation character in python"
this is my code
print("Length between sides: "+str((length*length)*2.6)+" \ 1.5 = "+str(((length*length)*2.6)\1.5)+" Units")
My problem is with \1.5 I have tried \1.5 but it doesn't work
Using python 2.7.2
The division operator is /, not \
The backslash \ is the line continuation character the error message is talking about, and after it, only newline characters/whitespace are allowed (before the next non-whitespace continues the "interrupted" line.
print "This is a very long string that doesn't fit" + \
"on a single line"
Outside of a string, a backslash can only appear in this way. For division, you want a slash: /.
If you want to write a verbatim backslash in a string, escape it by doubling it: "\\"
In your code, you're using it twice:
print("Length between sides: " + str((length*length)*2.6) +
" \ 1.5 = " + # inside a string; treated as literal
str(((length*length)*2.6)\1.5)+ # outside a string, treated as line cont
# character, but no newline follows -> Fail
" Units")
You must press enter after continuation character
Note: Space after continuation character leads to error
cost = {"apples": [3.5, 2.4, 2.3], "bananas": [1.2, 1.8]}
0.9 * average(cost["apples"]) + \ """enter here"""
0.1 * average(cost["bananas"])
The division operator is / rather than \.
Also, the backslash has a special meaning inside a Python string. Either escape it with another backslash:
"\\ 1.5 = "`
or use a raw string
r" \ 1.5 = "
Well, what do you try to do? If you want to use division, use "/" not "\".
If it is something else, explain it in a bit more detail, please.
As the others already mentioned: the division operator is / rather than **.
If you wanna print the ** character within a string you have to escape it:
print("foo \\")
# will print: foo \
I think to print the string you wanted I think you gonna need this code:
print("Length between sides: " + str((length*length)*2.6) + " \\ 1.5 = " + str(((length*length)*2.6)/1.5) + " Units")
And this one is a more readable version of the above (using the format method):
message = "Length between sides: {0} \\ 1.5 = {1} Units"
val1 = (length * length) * 2.6
val2 = ((length * length) * 2.6) / 1.5
print(message.format(val1, val2))
This is not related to the question; just for future purpose. In my case, I got this error message when using regex. Here is my code and the correction
text = "Hey I'm Kelly, how're you and how's it going?"
import re
When I got error:
x=re.search(r'('\w+)|(\w+'\w+)', text)
The correct code:
x=re.search(r"('\w+)|(\w+'\w+)", text)
I'm meant to use double quotes after the r instead of single quotes.