Python Forum
Syntax error while executing the Python code in Linux
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Syntax error while executing the Python code in Linux
#1
I have an input text file from which i am selecting certain lines which contains the specified strings. And then i remove replace and delete certain lines from the text file.I was working on the code in my local machine Spyder(Python 3.9) and it was working fine.But when i put the same code in GNU/Linux machine with Python 2.9 , its showing syntax error. I am not able to figure out the exact issue.Could you please help me out here. I am a beginner in Python.Giving below the code and the error i am facing

#!/usr/bin/python

import os
import re
import sys


strings = ["/opt","rm -rf","***"] # Search for strings and pick only those lines
with open(r"Input.txt", "r" ) as data:
    for deltaa in data:
        if any(x in deltaa for x in strings): #Check if any item in strings exits in deltaa
           with open("tmp1.txt", "a") as f:
            print (deltaa, file=f)
with open('tmp1.txt', 'r') as f:
    s = f.read().replace('cloud', '') #Replace the word cloud with blank
with open('tmp2.txt', 'w') as f:
    f.write(s)
inf = open("tmp2.txt")
stripped_lines = [l.lstrip() for l in inf.readlines()] # Delete the blank space
inf.close()

# write the new, stripped lines to a file
outf = open("tmp3.txt", "w")
outf.write("".join(stripped_lines))
outf.close()
file = open("tmp3.txt", "r")
lines = file.readlines()
lines = lines[1:] # Skip first line
new_lines = []
for line in lines:
   if "remove" not in line.strip(): #Delete the lines that contain remove
      new_lines.append(line)
file.close()
file = open("tmp4.txt", "w")
file.writelines(new_lines)
file.close()
Error:
File "./Script.py", line 13 print (deltaa, file=f) ^ SyntaxError: invalid syntax
Reply
#2
Python 3 programs generally don't run under Python 2. There were many changes going from 2 to 3. For example, print was a statement (no parenthesis) in python 2, but in python 3 it is a function.

Does your linux have a python3? From a shell, try this:
Output:
python3 --version
If you don't get an error, you can run your script using python3 in place of python. If not, you can install python 3. You should look for instructions for your linux version to make sure you don't damage your python 2 installation.
Reply
#3
There is no Python 2.9, it is probably 2.7.9 . Use python 3.
Reply
#4
(Jul-17-2023, 03:31 PM)deanhystad Wrote: Python 3 programs generally don't run under Python 2. There were many changes going from 2 to 3. For example, print was a statement (no parenthesis) in python 2, but in python 3 it is a function.

Does your linux have a python3? From a shell, try this:
Output:
python3 --version
If you don't get an error, you can run your script using python3 in place of python. If not, you can install python 3. You should look for instructions for your linux version to make sure you don't damage your python 2 installation.

The python version in linux is 2.6.6.It seems Python 3 cannot be installed in the Linux server atleast in the near future.I need to make this code compatible with 2.6. How can i achieve that.
Reply
#5
(Jul-18-2023, 05:23 AM)DivAsh Wrote: It seems Python 3 cannot be installed in the Linux server
This is very unlikely, unless your server is more than 15 years old. The python 2 branch is unmaintained since january 2020, which means you are trying to downgrade the code to an obsolete language. As far as I know, there is no automated tool to downgrade Python 3 code to Python 2. What is your OS and can you install software on this computer? Modern linux distributions come usually with Python 3.
Reply
#6
(Jul-18-2023, 07:12 AM)Gribouillis Wrote:
(Jul-18-2023, 05:23 AM)DivAsh Wrote: It seems Python 3 cannot be installed in the Linux server
This is very unlikely, unless your server is more than 15 years old.

My only option left now is to downgrade to Python 2.6 and make the code work. Thank you for helping me understand the difference in 2.x and 3.x. I did some workaround and changed the following line of code that i wrote in 3.9 with 2.x compatible code.Its working now and no syntax error
#with open("Enm1.txt", "a") as f:
            #print (deltaa, file=f)
           with open('tmp1.txt', 'w') as f:
            for r in deltaa:
             f.write(str(r))
Reply
#7
"with open("Enm1.txt", "a") as f:" is not the same as "with open('tmp1.txt', 'w') as f:". Not only do the file names differ, but one appends to an existing file ("a") while the other resets the file to empty ("w").

I also noticed you doing this:
with open(r"Input.txt", "r" ) as data:
    for deltaa in data:
        if any(x in deltaa for x in strings): #Check if any item in strings exits in deltaa
           with open("tmp1.txt", "a") as f:
            print (deltaa, file=f)
Opening and closing the file each time you want to write a line will be slow.
Maybe you should be doing this:
with open(r"Input.txt", "r" ) as data, open("tmp1.txt", "w") as f:  # Open input and output files
    for deltaa in data:
        if any(x in deltaa for x in strings):
           f.write(deltaa)
Doesn't that look cleaner?

If your version of python does not allow multiple opens in one context (may be a Python 2.7 feature), you can cascade the contexts.
with open(r"Input.txt", "r" ) as data:
    with open("tmp1.txt", "w") as f:  # Open input and output files
        for deltaa in data:
            if any(x in deltaa for x in strings):
               f.write(deltaa)
You are importing re. May as well use it. How about using a regular expression in place of any(). This regex looks for "/opt" or "rm -rf" or "***". If none are found, the search will return None.
import re

with open(r"Input.txt", "r") as data, open("tmp1.txt", "w") as f:
    for deltaa in data:
        if re.search(r"(/opt|rm -rf|\*\*\*)", deltaa):
            f.write(deltaa)
I like the re.search, but your use of "any()" is also pretty cool.

You used context managers for open at the top of the program. Why not here?
file = open("tmp3.txt", "r")
lines = file.readlines()
lines = lines[1:] # Skip first line
new_lines = []
for line in lines:
   if "remove" not in line.strip(): #Delete the lines that contain remove
      new_lines.append(line)
file.close()
Using the same pattern you used earlier in the code:
new_lines = []
with open("tmp3.txt", "r") as file:
    for line in file.readlines()[1:]:
        if "remove" not in line:
            new_lines.append(line.strip())  # Only strip lines you keep
But the real improvement is made by eliminating the temporary files. Your program reads a line. Checks if the line should be kept or ignored. Does some minor processing to lines that are kept, and writes the interesting, processed lines to a file. This can all be done in one pass with no temporary files.
import re

with open("Input.txt", "r") as inp, open("result.txt", "w") as out:
    next(inp)  # Skip the first line in the input file.
    for line in inp:
        # Ignore lines we don't want.
        if re.search(r"(/opt|rm -rf|\*\*\*)", line) is None:  # only want lines that include /opt, rm -rf, or ***
            continue
        if "remove" in line:  # don't want lines that include remove
            continue
        out.write(line.replace("cloud", ""))  # Remove cloud from the line
The continue statements jump to the start of the loop, ignoring lines that don't include one of the strings or include remove. For the lines that pass, remove "cloud" before writing to the result file (tmp4.txt in your program). There is no need for stripping the newline characters and adding it back in (writelines). The nicest part is it doesn't create files that have to be cleaned up later.
DivAsh likes this post
Reply
#8
Thanks a ton!!!As a beginner, this has helped me to learn on how to improvise the code.
Reply
#9
(Jul-19-2023, 06:41 AM)DivAsh Wrote: Thanks a ton!!!As a beginner, this has helped me to learn on how to improvise the code.

Try not printing file f but just Print(f). Also you spaced between print (f)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Is possible to run the python command to call python script on linux? cuten222 6 738 Jan-30-2024, 09:05 PM
Last Post: DeaD_EyE
  Syntax error for "root = Tk()" dlwaddel 15 1,214 Jan-29-2024, 12:07 AM
Last Post: dlwaddel
Photo SYNTAX ERROR Yannko 3 401 Jan-19-2024, 01:20 PM
Last Post: rob101
  Code with empty list not executing adeana 9 3,753 Dec-11-2023, 08:27 AM
Last Post: buran
  Code error from Fundamentals of Python Programming van Richard L. Halterman Heidi 12 1,716 Jul-25-2023, 10:32 PM
Last Post: Skaperen
  Code is returning the incorrect values. syntax error 007sonic 6 1,242 Jun-19-2023, 03:35 AM
Last Post: 007sonic
  Error 1064 (42000) when executing UPDATE SQL gratiszzzz 7 1,490 May-22-2023, 02:38 PM
Last Post: buran
  Compiles Python code with no error but giving out no output - what's wrong with it? pythonflea 6 1,586 Mar-27-2023, 07:38 AM
Last Post: buran
  syntax error question - string mgallotti 5 1,327 Feb-03-2023, 05:10 PM
Last Post: mgallotti
  Syntax error? I don't see it KenHorse 4 1,273 Jan-15-2023, 07:49 PM
Last Post: Gribouillis

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020