Here is the code from the exercise:
from sys import argv
script, user_name = argv
prompt = '> '
print "Hi %s, I'm the %s script." % (user_name, script)
print "I'd like to ask you a few questions."
print "Do you like me %s?" % user_name
likes = raw_input(prompt)
print "Where do you live %s?" % user_name
lives = raw_input(prompt)
print "What kind of computer do you have?"
computer = raw_input(prompt)
print """
Alright, so you said %r about liking me.
You live in %r. Not sure where that is.
And you have a %r computer. Nice.
""" % (likes, lives, computer)
Now I am running Windows 7 and I am running the CMD line with the code
python ex14.py myname
I get this error:
File "ex14.py", line 3
Python ex14.py, user_name
SyntaxError: invalid syntax
There is nothing wrong with the script among visible characters.
check there is no Unicode whitespace in the source e.g., NO-BREAK SPACE character. Create a new script in the same directory:
with open('ex14.py', 'rb') as file:
s = file.read()
print(repr(s)[:60])
u = s.decode('ascii') # this line should raise an error
# if there are bytes outside ascii
check Python version to make sure it is 2.7 (to interpret correctly error messages):
$ python -V
check that the file is not saved using utf-16/32 encodings (#abarnert's suggestion in the comments).
You should see many zero bytes '\x00' in the repr() results in this case.
install python2 and in terminal type
python2 ex14.py myname
will solve the problem
you are running the script in the latest python version
and the syntax of your code is for python version 2
that's why you are getting the syntax error
Related
I am trying to run a function called read_distribution.py in a Python package called RSeQC. However when I run the following command:
python3 read_distribution.py -i mysample.bam -r hg38_RefSeq.bed
I get the following error:
File "distribution.py", line 278
print "%-30s%d" % ("Total Reads",totalReads)
^
SyntaxError: invalid syntax
Lines 275-282 in the read_distribution.py code look like this:
except StopIteration:
print >>sys.stderr, "Finished\n"
print "%-30s%d" % ("Total Reads",totalReads)
print "%-30s%d" % ("Total Tags",totalFrags)
print "%-30s%d" % ("Total Assigned Tags",totalFrags-unAssignFrags)
print "====================================================================="
Is this a problem with my python version? I do not know enough Python to figure out the problem so any help is appreciated-Thanks!
I bet you're using Python 3.X. Starting with 3.0, the print statement became a function, requiring parentheses to be used like when calling any function. So the code you show needs to look like this to work in Python 3.X:
print("%-30s%d" % ("Total Reads",33))
print("%-30s%d" % ("Total Tags",33))
print("%-30s%d" % ("Total Assigned Tags",12))
print("=====================================================================")
There are scripts on the internet that will convert much of your Python 2.X code to 3.X if you have a bunch more of it to convert. Alternately, if you got the code from somewhere else, maybe they have a Python 3.X version available.
I believe this package was written in Python 2, which didn't have you putting ()'s after print, in Python 3 this changed to have you put ()'s after print, You're using Python 3.
I am very new to the language so I might need an ELI5 for the response.
I've created my ex1.py, checked all of the casing and syntax and it appears to be right?
print "Hellow World!"
print "Hello again"
print "i like typing this"
print "this is fun"
print 'Yay! printing!'
print "I'd much rather you 'n'."
print 'I "said" do not touch this!'
When I type: python ex1.py in terminal after navigating to the proper folder, the terminal displays the script, not powershell.
I've tried entering
[Environment]::SetEnvironmentVariable("Path", "$env:Path;C:\Python27", "User")
etc. string that is on page 8 of the book into PowerShell, but that doesn't seem to help.
In the filepath above, should I be replacing C:\Python27 with the literal filepath of where i have Python installed? Likewise, "User" with my username? Or do I enter the string literally as is?
Your code is fine but it seems your environment is not set correctly. Do the following:
Start powershell
[Environment]::SetEnvironmentVariable("Path", "$env:Path;C:\<directory_where_python.exe in installed>", "User")
Restart powershell (close it, then start it back up again)
Cd in directory that contains ex1.py
Execute python .\ex1.py
Please see if you have saved the file ex1.py properly.Check once.
You may have saved the file name first and later typed in the notepad and forgot to save the file.
I'm having a problem where if I run my python program in the windows terminal, text with inserted variables (%s) have wacky results, where as in the python shell it works fine.
Code:
print("Hi! What's your name?")
name = input("name: ")
print("Nice to meet you %s" % name)
print("%s is a good name." % name)
print("This line is only to test %s in the middle of the text." % name)
input("press enter to exit")
Result in python shell:
Result in cmd:
I'm using Windows 10 and python32 in case you needed to know.
This is a bug in the original 3.2.0 on Windows. The input() statement stripped off the "\n" but not the '\r', so the string input is hidden.
See https://bugs.python.org/issue11272
Quick fix:
name = input("name: ").rstrip()
It was fixed in 3.2.1. You really should upgrade your Python!
When using bash shell commands it would sometimes be usefull to pipe in python and write a short program and then maybe pipe that into something else. Im not finding a lot of documentation about writing python programs like this although it looks like the "-c" option is the option to use..but when writing even the simplest python program the compiler or should i say interpreter complains. See example below:
$ python -c "
import os
if os.path.isfile("test"):
print "test is a file"
else:
print "test is not a file"
"
When entering the last " the interpretor complains. This runs fine if i put it in a file but if i type it like that on the command line i get errors.
$ python -c "
import os
if os.path.isfile("test"):
print "test is a file"
else:
print "test is not a file"
"
Traceback (most recent call last):
File "<string>", line 4, in <module>
NameError: name 'test' is not defined
I have no idea why the interpretor is complaining here. Does someone know why this isnt working ?
What im really after is something like this:
$ cat somefile | python -c "
import re
check = re.search(pattern, <file input>)
"
I dont know how to access the output of cat in this situation so i just wrote it literally.
You are using double quotes inside double quotes which is ending the quoted string you are passing to python, in a place where you don't expect. Try replacing the outer quotes with single quotes, like I did here:
python -c '
import os
if os.path.isfile("test"):
print "test is a file"
else:
print "test is not a file"
'
If you are using single quotes to terminate the string you are passing to python, make sure to only use double quotes in your code. Additionally, if you can guarantee the availability of Bash as your shell, you can gain added awesome points by using heredoc format instead:
$ python <<EOF
> print "I can put python code here"
> EOF
I can put python code here
Another solution is to escape your inner double quotes so bash doesn't parse them. Like this:
$ python -c "
import os
if os.path.isfile(\"test\"):
print \"test is a file\"
else:
print \"test is not a file\"
"
Either use single quotes to enclose your short program or, if you want to use double quotes to enclose it, escape the quotes with \.
Examples:
1. Escaping quotes
$ python -c "
print \"hello\"
for i in (1,2,3):
print i
"
Output:
hello
1
2
3
2. With single quotes
$ python -c '
print "hello"
for i in (1,2,3):
print i
'
Of course, if you use single quotes to enclose your program and you want to use single quotes inside your python code, you'll have to escape them with \ ;-).
The output is the same.
You can use what is commonly called a "here document" (as in "use the document that is right here"). This avoids all quoting problems when using python -c "..." or python -c '...'
For example:
#!/bin/sh
python <<EOF
print "hello"
for i in (1,2,3):
print i
EOF
The "here document" takes an arbitrary marker ("EOF" is a common choice, but it can be any string you know doesn't occur anywhere else in the data), and accepts all data up unto it finds a line that contains that marker.
I'm having trouble in getting the following code to run, (it's exercise 15 from Zed Shaw's "Learn Python the hard way"):
from sys import argv
script, filename = argv
txt = open(filename)
print "Here's your file %r." % filename print txt.read()
print "Type the filename again: " file_again = raw_input("==>")
txt_again = open(file_again)
print txt_again.read()
txt.close() txt_again.close()
I try to run it from the terminal and get the following:
dominics-macbook-4:MyPython Dom$ python ex15_sample.txt
File "ex15_sample.txt", line 1
This is stuff I typed into a file.
^
SyntaxError: invalid syntax
Here's the contents of ex15_sample.txt:
"This is stuff I typed into a file.
It is really cool stuff.
Lots and lots of fun to have in here."
I'm banging my head off the wall! (Python 2.6.1, OS X 10.6.8)
python ex15_sample.txt
Why are you telling Python to run a text file? Don't you mean something more like
python ex15_sample.py ex15_sample.txt
or whatever you've called your Python program?