Python Use of File = defined variable - python

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.

Related

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.

Python 'print' statement and arguments

I'm an experienced C++ developer, but am just getting my feet wet with Python for a project at work. I'm having some basic problems and Google has been less than helpful. I suspect something about my environment is funny, but I have no clue how to diagnose it. I wrote a simple script that merely prints an argument to the screen, but I am getting an error when running it (python args.py):
Syntax Error: invalid syntax
File "args.py", line 4
print arg0
For reference, there is a carrot underneath the 0 of arg0. The script in question:
import sys
firstArg = sys.argv[0]
print firstArg
I'm sure this is something really dumb, but Python is such a foreign thing, coming from C++.
This seems pretty obvious. The traceback says you have a SyntaxError on line 4, therefore print firstArg isn't valid Python.
The not obvious part is that a lot of examples on the Internet use syntax like that. This is because in Python 2.X versions, print was a statement. Since Python 3.0, print is a function. Try print(firstArg) instead.
Protip: If you want to enable the print function in Python 2, use from __future__ import print_function.
I can understand that the print function of Python may be different for C or C++ developers because of its features.
The syntax that you use is for python 2 (now in End Of Life status). There are many differences between Python 2 and python 3.
In this case, the print was a statement in Python 2 but function in Python3.
Here is the correct syntax for print function in Python3.
print(firstArg)
Brackets are important because print is a function. The print function in Python has some parameters which make it even more powerful.

Python: invalid syntax in function print()

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

How to write a Python 2.6+ script that gracefully fails with older Python?

I'm using the new print from Python 3.x and I observed that the following code does not compile due to the end=' '.
from __future__ import print_function
import sys
if sys.hexversion < 0x02060000:
raise Exception("py too old")
...
print("x",end=" ") # fails to compile with py24
How can I continue using the new syntax but make the script fails nicely? Is it mandatory to call another script and use only safe syntax in this one?
The easy method for Python 2.6 is just to add a line like:
b'You need Python 2.6 or later.'
at the start of the file. This exploits the fact that byte literals were introduced in 2.6 and so any earlier versions will raise a SyntaxError with whatever message you write given as the stack trace.
There are some suggestions in this question here, but it looks like it is not easily possible. You'll have to create a wrapper script.
One way is to write your module using python 2.x print statement, then when you want to port it into python 3, you use 2to3 script. I think there are scripts for 3to2 conversion as well, although they seems to be less mature than 2to3.
Either way, in biggers scripts, you should always separate domain logic and input/output; that way, all the print statements/functions are bunched up together in a single file. For logging, you should use the logging module.

Categories