3

The command

python -c "print('hello')"

runs the code inside the quotes successfully, both in Linux (bash) and Windows (cmd.exe).

But how to pass code with newlines, with python -c?

Example: both

python -c "for i in range(10): if i % 2 == 0: print('hello')"
python -c "for i in range(10):\n    if i % 2 == 0:\n        print('hello')"

fail.


Example use case: I need to send a SSH command (with paramiko) to execute a short Python code on a remote server, so I need to pass one command like
ssh.exec_command('python -c "..."').

Basj
  • 41,386
  • 99
  • 383
  • 673

4 Answers4

4

You can use bash's $'foo' string syntax to get newlines:

python -c $'for i in range(10):\n if i % 2 == 0:\n  print("hello")'

(I'm using single space indents here)

For windows, you really should be using powershell, which has `n as a newline:

python -c "for i in range(10):`n if i % 2 == 0:`n  print('hello')"

In cmd.exe, it seems that you can use ^ to escape a newline, however I'm unable to test this currently so you should refer to this question's answers.

Aplet123
  • 33,825
  • 1
  • 29
  • 55
1

You can use a bash "heredoc" (also available ksh, and POSIX shells):

python <<EOF
import numpy as np
print(dir(np))
EOF
Mark Setchell
  • 191,897
  • 31
  • 273
  • 432
0

One way could be with exec(), what make strings executable. It looks bad, but it works.

python -c "exec(\"for i in range(10):\n if i % 2 == 0:\n  print('hello')\")"
Patrik
  • 499
  • 1
  • 7
  • 24
0

While not using -c it is worth mentioning that, if using Bash, you can pipe echoed code directly to python.

echo -e 'for i in range(10):\n if i % 2 == 0:\n  print("hello")' | python

Following Aplet123's lead and using using single space indents.

mattst
  • 13,340
  • 4
  • 31
  • 43