A Python script to execute Python code like "perl -ne"

I wrote a small utility script that can be used to run a small snippet of Python code like "perl -ne". I find it very useful for my needs. Hope it helps you too. Any suggestions welcome.
You can find the script as a gist here.

Comments

To create a Python script that executes Python code similarly to "perl -ne," you can use the sys module in Python. The "perl -ne" command reads input line by line and applies the given Perl code to each line. In Python, you can achieve this functionality using a loop and the sys.stdin stream for reading input. Here's a sample Python script:

python

import sys

# Define the Python code to be executed on each line
python_code = '''
# Your Python code here
# Example: To print each line, you can use the following:
print(line, end='')
'''

# Function to execute Python code for each line of input
def execute_python_code():
for line in sys.stdin:
# Execute the Python code for each line
exec(python_code, {'line': line})

if __name__ == "__main__":
execute_python_code()

Popular posts from this blog

Gotchas with DBCP

A note on Java's Calendar set() method

The mysterious ORA-03111 error