Python: invalid syntax in function print() - python

I am using Python 2.7.
When I try to print a simple string to a file, I get the following error:
Syntax error: invalid tuple
Syntax error while detecting tuple
minimal example:
fly = open('workfile', 'w')
print('a', file=fly)
writing to the same file via fly.write('a') works just fine.

You are using the Python 3 syntax in Python 2.
In Python 2, it's like this:
print >> fly, 'a'
However, a better idea is to do this:
from __future__ import print_function
Which will enable the Python 3 syntax if you are using Python 2.6 or 2.7.
See also: http://docs.python.org/2/library/functions.html#print

Check the documentation
Note This function is not normally available as a built-in since the name print is recognized as the print statement. To disable the statement and use the print() function, use this future statement at the top of your module:
from future import print_function

Related

Is there a way to compile the Python code ignore syntax?

I am making code that works on both Python 2 and Python 3.
But there was no problem in theory, but there was a Python problem.
Now I'm build and use both Python 2.7.5 and Python 3.7.4.
This is part of my code
ex)
if sys.version_info < (3,):
print(keys),;
print(values)
else:
print(keys,'/ ', end='')
print(values)
This code that checks Python version with sys.version, corresponding 'if' will be working.
But, of course there is a syntax error.
Python 2 does not support [end=''].
In my opinion...
Even if you actually ignore it and act on it, there's no problem code.
I tried 'Try-except', but syntax errors were not ignored.
How can both Python2 and Python3 not change lines while weaving compatible codes?
Import the package print_function and try
from __future__ import print_function
In this particular case, just get the Python 3 print function in both Python 2 and Python 3 by adding:
from __future__ import print_function
to the very top of your file, then only use the Python 3 syntax.
As for avoiding the SyntaxError from actually incompatible constructs that can't be fixed with a __future__ import, the only solutions are putting the incompatible code in separate modules (a public module can do version testing to import the implementations from the private module appropriate to the Python version), or evaling a string containing the code for the appropriate version (exec won't typically work, because it also changed from keyword statement to built-in function in the transition; eval+compile is the same in both though).
There is no way to just "turn off syntax checking", because invalid syntax definitionally means the parser has encountered an unrecoverable error; you don't want it to try to stumble onwards, guessing at what everything else means in the context of the garbage state it was left in.

Flask-Script invalid syntax error [duplicate]

When I try to use a print statement in Python, it gives me this error:
>>> print "Hello, World!"
File "<stdin>", line 1
print "Hello, World!"
^
SyntaxError: Missing parentheses in call to 'print'
What does that mean?
This error message means that you are attempting to use Python 3 to follow an example or run a program that uses the Python 2 print statement:
print "Hello, World!"
The statement above does not work in Python 3. In Python 3 you need to add parentheses around the value to be printed:
print("Hello, World!")
“SyntaxError: Missing parentheses in call to 'print'” is a new error message that was added in Python 3.4.2 primarily to help users that are trying to follow a Python 2 tutorial while running Python 3.
In Python 3, printing values changed from being a distinct statement to being an ordinary function call, so it now needs parentheses:
>>> print("Hello, World!")
Hello, World!
In earlier versions of Python 3, the interpreter just reports a generic syntax error, without providing any useful hints as to what might be going wrong:
>>> print "Hello, World!"
File "<stdin>", line 1
print "Hello, World!"
^
SyntaxError: invalid syntax
As for why print became an ordinary function in Python 3, that didn't relate to the basic form of the statement, but rather to how you did more complicated things like printing multiple items to stderr with a trailing space rather than ending the line.
In Python 2:
>>> import sys
>>> print >> sys.stderr, 1, 2, 3,; print >> sys.stderr, 4, 5, 6
1 2 3 4 5 6
In Python 3:
>>> import sys
>>> print(1, 2, 3, file=sys.stderr, end=" "); print(4, 5, 6, file=sys.stderr)
1 2 3 4 5 6
Starting with the Python 3.6.3 release in September 2017, some error messages related to the Python 2.x print syntax have been updated to recommend their Python 3.x counterparts:
>>> print "Hello!"
File "<stdin>", line 1
print "Hello!"
^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print("Hello!")?
Since the "Missing parentheses in call to print" case is a compile time syntax error and hence has access to the raw source code, it's able to include the full text on the rest of the line in the suggested replacement. However, it doesn't currently try to work out the appropriate quotes to place around that expression (that's not impossible, just sufficiently complicated that it hasn't been done).
The TypeError raised for the right shift operator has also been customised:
>>> print >> sys.stderr
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for >>: 'builtin_function_or_method' and '_io.TextIOWrapper'. Did you mean "print(<message>, file=<output_stream>)"?
Since this error is raised when the code runs, rather than when it is compiled, it doesn't have access to the raw source code, and hence uses meta-variables (<message> and <output_stream>) in the suggested replacement expression instead of whatever the user actually typed. Unlike the syntax error case, it's straightforward to place quotes around the Python expression in the custom right shift error message.
Unfortunately, the old xkcd comic isn't completely up to date anymore.
Since Python 3.0 you have to write:
print("Hello, World!")
And someone has still to write that antigravity library :(
There is a change in syntax from Python 2 to Python 3.
In Python 2,
print "Hello, World!"
will work but in Python 3, use parentheses as
print("Hello, World!")
This is equivalent syntax to Scala and near to Java.
Basically, since Python 3.x you need to use print with parenthesis.
Python 2.x: print "Lord of the Rings"
Python 3.x: print("Lord of the Rings")
Explanation
print was a statement in 2.x, but it's a function in 3.x. Now, there are a number of good reasons for this.
With function format of Python 3.x, more flexibility comes when printing multiple items with comma separated.
You can't use argument splatting with a statement. In 3.x if you have a list of items that you want to print with a separator, you can do this:
>>> items = ['foo', 'bar', 'baz']
>>> print(*items, sep='+')
foo+bar+baz
You can't override a statement. If you want to change the behavior of print, you can do that when it's a function but not when it's a statement.
If your code should work in both Python 2 and 3, you can achieve this by loading this at the beginning of your program:
from __future__ import print_function # If code has to work in Python 2 and 3!
Then you can print in the Python 3 way:
print("python")
If you want to print something without creating a new line - you can do this:
for number in range(0, 10):
print(number, end=', ')
In Python 3, you can only print as:
print("STRING")
But in Python 2, the parentheses are not necessary.
I could also just add that I knew everything about the syntax change between Python2.7 and Python3, and my code was correctly written as print("string") and even
print(f"string")...
But after some time of debugging I realized that my bash script was calling python like:
python file_name.py
which had the effect of calling my python script by default using python2.7 which gave the error. So I changed my bash script to:
python3 file_name.py
which of coarse uses python3 to run the script which fixed the error.
print('Hello, World!')
You're using python 3, where you need brackets when printing.
Outside of the direct answers here, one should note the other key difference between python 2 and 3. The official python wiki goes into almost all of the major differences and focuses on when you should use either of the versions. This blog post also does a fine job of explaining the current python universe and the somehow unsolved puzzle of moving to python 3.
As far as I can tell, you are beginning to learn the python language. You should consider the aforementioned articles before you continue down the python 3 route. Not only will you have to change some of your syntax, you will also need to think about which packages will be available to you (an advantage of python 2) and potential optimizations that could be made in your code (an advantage of python 3).
So I was getting this error
from trp import BoundingBox, Document
File "C:\Users\Kshitij Agarwal\AppData\Roaming\Python\Python39\site-packages\trp\__init__.py", line 31
print ip
^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print(ip)?
This is a Python package error, in which Python2 has been used and you are probably running this on Python3.
One solution could be to convert Python2 print something to Python3 print(something) for every line in each file in the package folder, which is not a good idea😅. I mean, you can do it but still there are better ways.
To perform the same task, there is a package named 2to3 in Python which converts Python2 scripts to Python3 scripts. To install it, execute the 👇 command in terminal..
pip install 2to3
Then change the directory in terminal to the location where the package files are present, in my case - C:\Users\Kshitij Agarwal\AppData\Roaming\Python\Python39\site-packages\trp
Now execute the command 👇
2to3 . -w
and voila, all the Python2 files in that directory will be converted to Python3.
Note:- The above commands hold true for other operating systems as well. Only Python package path will vary as per the system.
print "text" is not the way of printing text in python as this won't work
print("text") will print said text on your screen in the command line

Python Use of File = defined variable

I am attempting to output a file that was read and altered.
new_file = open("MC_QS_MODIFIED.inp","w")
...
...
print( final_data , file=new_file )
new_file.close()
and python is taking exception to the = in print(final_data, file=new_file )
It worked at home but now that I am attempting to run the script at work, Python 2.7.6 is giving me a syntax error. I am still pretty new to this, so I don't know if my code is 3.0+ and 2.7.6 doesn't like it or what.
In Python 2, print() is not a function but a statement, unless you tell Python you want to use the Python 3 syntax.
Put this at the top of your file:
from __future__ import print_function
to disable the print statement in the compiler so you can use the print() function instead.
You may run into other problems if you developed on Python 3 and try to run on Python 2, however.

Reposurgeon gives me a SyntaxError when using exec, why?

Using reposurgeon and trying to extend its functionality, I am faced with:
reposurgeon: invalid syntax in extension function
which translates to a SyntaxError extension raised from the execfile() call in RepoSurgeon.do_exec(). What gives? The code I am trying to exec is as simple as:
print "Hello world"
I have also used the Python CLI and execfile and there are no complaints whatsoever?
Used version: reposurgeon 3.10
This one took me a while to figure out, which is why I am posting it here.
The key is indeed in the single line of code we're trying to "source". While this is perfectly valid Python 2.x code, reposurgeon uses the print function from Python 3.x by doing:
from __future__ import print_function
Which causes print to require the use of parentheses, as it makes print a function instead of a statement.
Obviously we're running our extension code in the context of reposurgeon, which means that we're dependent on the rules it defines.
See this document.
Hence the following will work just fine:
print("Hello world")

Python: How to import 2.7 module into 3.4 program?

Question:
Is it possible to import a module I wrote in python 2.7 into a 3.4 program that I wrote?
Background:
I've tried doing this and as expected it throws a SyntaxError: Invalid Syntax, once it sees the first print "string literal" statement instead of 3.4's print(). There are a few additional incompatible code snippets, like import Tkinter instead of tkinter. The 2.7 module must remain in 2.7 because one of its dependencies doesn't seem to work in 3.X (a python binding for the switchvox api).
I'm building a display app that will call any module specified in its config file and display that module's output (a string, or in the future possible a dict) in a tkinter widget. All my program needs to do is import the 2.7 module and call one function once (every x number of seconds) to receive that string of data.
You can make your python 2.7 code be 3.4 compatible - this way you can import it from 3.4 and use the same classes and functions.
For running you have to run it on different process using python 2.7 - using subprocess.
Assume main27.py has the following line:
print 1
To run it using subprocess, you do as follow:
import subprocess
cmd = [r'c:\python27\python.exe', 'main27.py']
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
Than in stdout you have the following output:
1
For more complex data exchange you can use json or pickle using files.
Indeed it is possible to make your code compatible with both versions. The obvious one and potentially more annoying is the print statement.
Let's say you have the following Python 2.x code:
name = "beautiful"
print "Hallo"
print "I mean, hallo ", name
The first line works fine in both versions. The second line, can just become:
print("Hallo")
Which is compatible with both versions too. Note that you can use single or double quotes.
The last line requires a little trick, otherwise, Python 2 will print the brackets as well. In order to make it work the same way in Python 2 as it does in Python 3, you have to import print_function from future, at the top of your module.
In summary, this is the dual compatible code:
#Works in Python 2.x or Python 3.x
from __future__ import print_function
print("Hallo")
print("I mean, hallo ", name)
See this cheat sheet for more details.

Categories