Repeated errors while working with Portable Python [duplicate] - python

This question already has answers here:
Syntax error on print with Python 3 [duplicate]
(3 answers)
Closed 9 years ago.
Note: This was not answered by the question that was marked as the original. This is more than just a Python v2 vs v3 problem, which I explain in the comments below.
Original post:
I am trying to learn Python at work, so I am currently using Portable Python 3.2.1.1 (which will henceforth be referred to as PP). (I mention this because this problem doesn't happen at home when I use my Mac and regular Python.)
I am working through exercise 16 of Learning Python the Hard Way (http://learnpythonthehardway.org/book/ex16.html). I've heard this isn't the best learning tool, but I am a complete programming n00b and I'm a hands-on learner. If you have any better suggestions, I'm open!
The first few lines of the exercise read:
from sys import argv
script, filename = argv
print "We're going to erase %r." % filename
print "If you don't want that, hit CTRL-C (^C)."
My script is titled Ex16.py and the file I am using is Python.txt, and both of these are in the same folder as the PP .exes. I don't think that's necessary, but hoped maybe it would fix the problem... negative. When I press "Run" in PP, it doesn't work because argv requires you provide an argument when you start the script: python Ex16.py Python.txt
When I launch Python.exe (which, in PP is Portable-Python.exe), I get the standard Python prompt, >>>, but whatever I enter I get the same error message:
File "<stdin>", line 1
with whatever I've just tried repeated back to me with the marker to
indicate where the problem is. (has not been helpful so far)
SyntaxError: invalid syntax
I have tried typing the following at the >>> prompt:
python Ex16.py Python.txt,,
Ex16.py Python.txt,,
"%PATH&\Ex16.py" "%PATH%\Python.txt" (with the actual filepaths),,
print 'hello world'
I just keep getting the same invalid syntax error over and over. Even a basic print command returned an invalid syntax error. The only one that triggered a different error was the one where I tried whole filepaths. That one returned:
File "<stdin>", line 1
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in
position 2-3: truncated \UXXXXXXXX escape
Yes, I have Googled the crap outta both errors. I read that sometimes the problem is not doubling the backspaces, so I tried that, too, putting two \ where just one had been before in both filepaths. I even tried putting — # -*- coding: utf-8 -*- at the beginning of the script thinking maybe there was some unicode error. That, with the full filepaths, resulted in the same unicode error mentioned earlier.
Yes, I have checked that my code is matching that in the exercise.
Yes, this works at home on non-PP.
All this leads me to believe that the problem is probably in the way I'm trying to run the scripts in PP (but why won't print work?), but I haven't a clue what I'm doing wrong.
Thanks!

print is a function in Python 3:
print('my string with content and the like')
It is no longer supported as being a 'statement'. You might want to check out a list of things that changed from python2.x to python3.x (there's a number of incompatibilities). Also, you might be better off finding a tutorial using Python3.

You have to type:
Portable-Python.exe Ex16.py Python.txt
at your command prompt. To get a command prompt, press WindowsKey-R, then type "cmd" and press enter. You should now be looking at something like c:\>. Navigate to your portable python installation by using the cd command.

Related

if statement to identify directory path [duplicate]

This question already has answers here:
How should I write a Windows path in a Python string literal?
(5 answers)
Closed 15 days ago.
I've got watchdog and pyaudio playing together so if either of two directories is modified I hear a sound.
Now I'm trying to get a different sound for each directory. Watchdog can print the path that triggered it, so I'm trying to use that difference to fire each sound.
def on_modified(self, event,):
x = event.src_path
print(x)
if x == 'c:/WATCHDOGTEST\x.csv':
pyaudio_01.PLAY_SOUND()
if x == 'c:/WATCHDOGTEST2\x.csv':
pyaudio_02.PLAY_SOUND()
The print(x) works fine:
c:/WATCHDOGTEST2\x.csv
however - the if statement won't work - I get:
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 16-17: truncated \xXX escape
Any ideas appreciated!
Using \x in the string, python interprets anything after \x as hexadecimal charector, so you need to escape this charector, using one more slash.
So your value will be c:/WATCHDOGTEST\\x.csv
Or you can turn it into raw string using r formater, r'c:/WATCHDOGTEST\x.csv', this is the best way, beacuse it automatically ignores any special charectory if present.
OK just figured it out - I added a forward slash to the target directory to get rid of the backslash it added itself, now it works. Doh.
using built-in library pathlib would be more easy.
PureWindowsPath('c:/Program Files/').match(event.src_path)
Pure path objects provide path-handling operations which don’t actually access a filesystem. There are three ways to access these classes, which we also call flavours.

Python encoding issue in script if string not hard-coded

I have an encoding issue with strings I get from an external source.
This source sends the strings encoded to me and I can decode them only if they are part of the script's code.
I've looked at several threads here and even some recommended tutorials (such as this one) but came up empty.
For example, if I run this:
python -c 'print "gro\303\237e"'
I get:
große
Which is the correct result.
But If I use it in a script, such as:
import sys
print sys.argv[1]
and call it like test.py "gro\303\237e", I get:
gro\303\237e
I intend to write the correct string to syslog, but I can't seem to get this to work.
Some data on my system:
- Python 2.7.10
- CentOS Linux
- LANG=en_US.UTF-8
- LC_CTYPE=UTF-8
I will appreciate any help, please let me know if you need more information.
Thanks!
If you really have the chars gro\303\237e which is something else as "gro\303\237e" (the first one are the chars g r o \ 3 0 3 \ 2 3 7, the second one is the chars g r o ß e) you can use decode("escape_string") as described in this SO answer
Note that this is probably an encoding error whoever produced the data. So it may contain other errors that you can not fix with this method.
This will work:
import sys
import ast
print ast.literal_eval('b"%s"' % sys.argv[1]).decode("utf-8")
But please read about literal_eval first to make sure it suits your needs (I think it should be safe to use but you should read and make sure).

Python print in terminal returning 'invalid syntax'

Im using the terminal on my mac to run some python and when i try to print a string i get an invalid syntax error.
Michaels-MBP:~ mike$ python text.py
File "text.py", line 2
print(‘hi’)
^
SyntaxError: invalid syntax
I've tried it with single quotes and with and without parentheses but i keep getting that error, what is wrong.
Should be:
print('hi')
You have proper British quotes ‘foo’. Those are the right symbols to use when writing human-readable texts, but Python wants actual single quotes '.
Your editor probably has some kind of smart-quotes feature enabled, it is wise to turn this off when writing code (e.g. configure your editor to detect extensions like .py).

Python Printing in Terminal

I am sorry to post what I think may be a very basic question, but my attempts at solving this have been futile, and I can't find a useful solution that has already been suggested to similar questions on this site.
My basic issue is this: I am attempting to run a file (coding UTF-8) as a program in Mac terminal (running Python 2.7.5). This works fine when I print the results of a mathematical operations, but for some reason I cannot print a simple string of characters.
I have tried running both:
# coding: utf-8
print "Hello, World."
exit()
and
# coding: utf-8
print("Hello, World.")
exit()
Both return an invalid syntax error, with the caret pointing at first set of quotation marks that I've used. What am I missing here?
Thank you for your help!
It turned out that I needed to disable smart quotes in TextEdit.

Help me make my Python 2 code work in Python 3

import math,sys,time;i=0
while 1: sys.stdout.write("\r"+':(_​_)'[:3+int(round(math.sin(​i)))]+'n'+':(__)'[3+int(ro​und(math.sin(i))):]);sys.s​tdout.flush();time.sleep(.​15);i+=0.5*math.pi
I wrote that simple program in Python 2 a long time ago and it worked fine but it has syntax errors in Python 3. I would greatly appreciate if someone could help me update it to be Python 3 compliant. Thanks.
I pasted your code in a file, saved it, then opened it in a Python shell:
In [10]: f=open('test2.py')
In [11]: content=f.read()
In [12]: content
Out[12]: '#!/usr/bin/env python\n# coding: utf-8\n\nimport math,sys,time;i=0\nwhile 1: sys.stdout.write("\\r"+\':(_\xe2\x80\x8b_)\'[:3+int(round(math.sin(\xe2\x80\x8bi)))]+\'n\'+\':(__)\'[3+int(ro\xe2\x80\x8bund(math.sin(i))):]);sys.s\xe2\x80\x8btdout.flush();time.sleep(.\xe2\x80\x8b15);i+=0.5*math.pi\n'
Notice the '\xe2\x80\x8b' bytes sprinkled here and there. These are ZERO WIDTH SPACE characters encoded in utf-8:
In [24]: print(repr(u'\N{ZERO WIDTH SPACE}'.encode('utf-8')))
'\xe2\x80\x8b'
This is why your code is giving rise to SyntaxErrors.
Just retype it (or copy the code below) and it will run in Python3:
import math, sys, time; i=0
while 1: sys.stdout.write('\r'+':(__)'[:3+int(round(math.sin(i)))]+'n'+':(__)'[3+int(round(math.sin(i))):]); sys.stdout.flush(); time.sleep(0.15); i+=0.5*math.pi
The problems has nothing to do with your Python version. You've got weird characters in your code.
I pasted it in Metapad and a bunch of ? showed up, I assume meaning unprintable character.
Just retype it and it will work fine, or find a text editor which will show those characters and delete them, or use Python to delete any non-printable characters.
Indeed, #agf is correct. There was a weird character between the underscores in the first (__). Corrected (and works fine with Python 3):
import math,sys,time;i=0
while 1: sys.stdout.write("\r"+':(__)'[:3+int(round(math.sin(i)))]+'n'+':(__)'[3+int(round(math.sin(i))):]);sys.stdout.flush();time.sleep(.15);i+=0.5*math.pi
Use 2to3 on your python installation. It comes standard (I think) with 2.7.2+

Categories

Resources