Comma does not separate lines of print in python34 on windows8? - python

I am learning python34 and I read here in my course book the following line:
"The comma separating the two print() commands in this file instructs Python to no start a new
line."
I am guessing by "no" they actually mean not?
Using the next script:
#!/usr/bin/env python3
print ("Hello from a Python file!"),
print ("Welcome to Python!")
And I have the following example of its execution on mac:
$ python3 ~/Desktop/Python/Hello.py
Hello from a Python file! Welcome to Python!
But my windows8 gives me this output:
c:\f>a.py
Hello from a Python file!
Welcome to Python!
I am running the file via cmd without the Python command (as shown above), since it doesn't work otherwise...
I added manually the system Environment Variables path to Python default installation
folder (C:\Python34)

The comma doesn't work in Python3, see what's new in Python 3. Also see the docs for print function in Python 3.
Old: print x, # Trailing comma suppresses newline
New: print(x, end=" ") # Appends a space instead of a newline
Your example would be:
>>> def test():
... print("Hello from a Python file!", end=" ")
... print("Welcome to Python!")
...
>>> test()
Hello from a Python file! Welcome to Python!

Output in Python3
Hello from a Python file!
Welcome to Python!
Output in Python2
Hello from a Python file! Welcome to Python!
This is because the comma notation has been removed as print has been made a function in 3 whereas it was a keyword in 2.
You can achieve what you want by using
print ("Hello from a Python file!",end = ' ')
print ("Welcome to Python!")
This making use of keyword arguments of the print function in python3

Related

Invalid Syntax Error in Python package RSeQC

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.

Learn Python the Hard Way, Ex 2; Powershell not outputting ex1.py?

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.

Writing python scripts directly on the command line

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.

How to read next logical line in python

I would like to read the next logical line from a file into python, where logical means "according to the syntax of python".
I have written a small command which reads a set of statements from a file, and then prints out what you would get if you typed the statements into a python shell, complete with prompts and return values. Simple enough -- read each line, then eval. Which works just fine, until you hit a multi-line string.
I'm trying to avoid doing my own lexical analysis.
As a simple example, say I have a file containing
2 + 2
I want to print
>>> 2 + 2
4
and if I have a file with
"""Hello
World"""
I want to print
>>>> """Hello
...World"""
'Hello\nWorld'
The first of these is trivial -- read a line, eval, print. But then I need special support for comment lines. And now triple quotes. And so on.
You may want to take a look at the InteractiveInterpreter class from the code module .
The runsource() method shows how to deal with incomplete input.
Okay, so resi had the correct idea. Here is my trivial code which does the job.
#!/usr/bin/python
import sys
import code
class Shell(code.InteractiveConsole):
def write(data):
print(data)
cons = Shell()
file_contents = sys.stdin
prompt = ">>> "
for line in file_contents:
print prompt + line,
if cons.push(line.strip()):
prompt = "... "
else:
prompt = ">>> "

exercise 14 learning python the hard way

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

Categories