How do i run a single line in python from terminal?

From Wikibooks, open books for an open world

Jump to navigation Jump to search

Python can run one-liners from an operating system command line using option -c:

  • python -c "print(3.0/2)"
    • Calculates and outputs the result.
  • python -c "import math;print(math.sin(1))"
    • Imports a module required and outputs sine value.
  • python -c "for i in range(1,11):print(i)"
    • Uses a loop to output numbers from 1 to 10.
  • python -c "for i in range(1,11):for j in range(1,11): print(i,j)"
    • Does not work; two loops in a line are an invalid syntax.
  • python -c "for i, j in ((i,j) for i in range (1,11) for j in range(1,11)): print(i, j)"
    • Outputs pairs using two analogues of loop within a comprehension.
  • echo hey | python -c "import sys,re;[sys.stdout.write(line) for line in sys.stdin if re.search('he.', line)]"
    • Acts as grep: outputs each line of the input containing a substring matching a regular expression. Not a Python one-liner strength.
  • echo hallo | python -c "import sys,re;[sys.stdout.write(re.sub('h[au]llo', 'hello', line)) for line in sys.stdin]"
    • Acts as sed: for each line of the input, performs a regex replacement and outputs the results. Again, not a Python one-liner strength.
  • python -m calendar
    • Outputs a year's calendar using calendar module.
  • python -c "import playsound as p;p.playsound(r'C:\WINDOWS\Media\notify.wav')"
    • On Windows, plays notification sound. Requires installation of playsound module. The module works across platforms; what is Windows specific above is the file path.
  • Powerful Python One-Liners, wiki.python.org

  • The flag to run a single command is -c and not -m.
  • You also need to import uuid so you can use it.
  • You also need to use print() to actually see some output.
  • Finally the whole passed command has to be in quotes.

$ python3 - c "import uuid; print(uuid.uuid4().hex)"
8e79508445 db4aca91bb0990529fdd89


Suggestion : 2

Summary: To make a Python one-liner out of any multi-line Python script, replace the new lines with a new line character '\n' and pass the result into the exec(...) function. You can run this script from the outside (command line, shell, terminal) by using the command python -c "exec(...)". ,Just make sure to use the python -c prefix and then pack the single-line multi-liner into a string value that is passed as an argument to the python program.,If you have code that spans multiple lines, you can pack it into a single-line string by using the newline character '\n' in your string:,Problem: Given a multi-line code script in Python. How to execute this multi-line script in a single line of Python code? How to do it from the command line?

Example: Say, you have the following for loop with a nested if statement in the for loop body. You want to run this in a single line from your command line?

x = 10
for i in range(5):
   if x % 2 == 0:
   print(i)
else :
   print(x)
x = x - 1

''
'
0
9
2
7
4
   ''
'

If you have code that spans multiple lines, you can pack it into a single-line string by using the newline character '\n' in your string:

# Method 1
exec('x = 10\nfor i in range(5):\n    if x%2 ==0: print(i)\n    else: print(x)\n    x = x-1')

This one-liner code snippet is semantically equivalent to the above nested for loop that requires seven lines of code! The output is the same:


Summary: To make a Python one-liner out of any multi-line Python script, replace the new lines with a new line character '\n' and pass the result into the exec(...) function. You can run this script from the outside (command line, shell, terminal) by using the command python -c "exec(...)".

[Don't Do This At Home] How To One-Linerize Every Multi-Line Python Script & Run It From The Shell

Problem: Given a multi-line code script in Python. How to execute this multi-line script in a single line of Python code? How to do it from the command line?

Example: Say, you have the following for loop with a nested if statement in the for loop body. You want to run this in a single line from your command line?

x = 10
for i in range(5):
    if x%2 == 0:
        print(i)
    else:
        print(x)
    x = x - 1

'''
0
9
2
7
4
'''

The code prints five numbers to the shell. It only prints the odd values of x. If x takes an even value, it prints the loop variable i.

Let’s have a look at the three methods to solve this problem!

  • Method 1: exec()
  • Method 2: From Command-Line | python -c + exec()
  • Method 3: Use Ternary Operator to One-Linerize the Code
  • Python One-Liners Book: Master the Single Line First!
  • Programmer Humor

Method 1: exec()

You can write any source code into a string and run the string using the built-in exec() function in Python. This is little known—yet, hackers often use this to pack malicious code into a single line that’s seemingly harmless.

If you have code that spans multiple lines, you can pack it into a single-line string by using the newline character '\n' in your string:

# Method 1
exec('x = 10\nfor i in range(5):\n    if x%2 ==0: print(i)\n    else: print(x)\n    x = x-1')

This one-liner code snippet is semantically equivalent to the above nested for loop that requires seven lines of code! The output is the same:

'''
0
9
2
7
4
'''

Try it yourself in our interactive code shell:

Exercise: Remove the else branch of this code. What’s the output? Run the code to check if you were right!

Method 2: From Command-Line | python -c + exec()

Of course, you can also run this code from your Win/Linux/Mac command line or shell.

How do i run a single line in python from terminal?

Just make sure to use the python -c prefix and then pack the single-line multi-liner into a string value that is passed as an argument to the python program.

This is how it looks in my Win 10 powershell:

PS C:\Users\xcent> python -c "exec('x = 10\nfor i in range(5):\n    if x%2 ==0: print(i)\n    else: print(x)\n    x = x-1')"
0
9
2
7
4

Method 3: Use Ternary Operator to One-Linerize the Code

Of course, you can also create your own semantically-equivalent one-liner using a bit of creativity and Python One-Liner skills (e.g., acquired through reading my book “Python One-Liners” from NoStarch)!

In this code, you use the ternary operator:

# Method 3
for i in range(5): print(10-i) if i%2 else print(i)

You can easily convince yourself that the code does the same thing in a single line!

Python One-Liners Book: Master the Single Line First!

Python programmers will improve their computer science skills with these useful one-liners.

How do i run a single line in python from terminal?

Python One-Linerswill teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.

The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms.

Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments.

You’ll also learn how to:

  • Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
  • Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
  • Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
  • Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
  • Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting

By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.

Get your Python One-Liners on Amazon!!

Programmer Humor

Question: How did the programmer die in the shower? ☠️

Answer: They read the shampoo bottle instructions:
Lather. Rinse. Repeat.

How do i run a single line in python from terminal?

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.

To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.

His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.

How do I run a line in terminal in Python?

To run Python scripts with the python command, you need to open a command-line and type in the word python , or python3 if you have both versions, followed by the path to your script, just like this: $ python3 hello.py Hello World!

Can I run Python line by line?

One thing that distinguishes Python from other programming languages is that it is interpreted rather than compiled. This means that it is executed line by line, which allows programming to be interactive in a way that is not directly possible with compiled languages like Fortran, C, or Java.

How do I run a Python script from the command line with example?

The most basic and easy way to run a Python script is by using the python command. You need to open a command line and type the word python followed by the path to your script file, like this: python first_script.py Hello World! Then you hit the ENTER button from the keyboard and that's it.