0

Is it possible to get run multiple commands in Python from command line in Windows?

Here's what I tried on command line in Windows.

python -c print(4)\nprint(5)

The error I received was the following:

SyntaxError: unexpected character after line continuation character

Is what I wrote above even possible to do?

Can I run multiple statements such as the following:

python -c a=5\nb=3\nprint(a+b)

And if so, how?

martineau
  • 119,623
  • 25
  • 170
  • 301

1 Answers1

0

Semicolons, instead of newlines

python -c "print(4); print(5)"
# prints 4, and then 5
python -c "a=5; b=3; print(a+b)"
# prints 8
Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53
  • Newlines work fine, if you actually pass a newline, and not the literal characters ``\`` and `n`, as part of the argument. – chepner Apr 16 '19 at 20:50
  • Thanks Green Cloak Guy. What's the rationale behind using the double quotes? I think I came across it in some documentation, but I didn't understand why it's necessary. – winston the dog Apr 17 '19 at 21:09
  • The double-quotes tell your shell to treat everything inside of them *as a single token*, instead of as separate tokens - regardless of any separators or whatever. In this case, they're basically required - the only way to pass a line break is to put it inside quotes (otherwise it ends the line in the shell; `\n` doesn't really work on the shell, as you've discovered), and `;` would do the same thing if it wasn't in quotes. Single-quotes should work just as well (at least in Bash they're interchangeable; I don't know if that's the case in Powershell) – Green Cloak Guy Apr 18 '19 at 00:15
  • Thanks, I also noticed that some parameters within functions don't seem to work in terminal either. For example, setting a,b=1,2 in Python then trying to print as print(a,b,sep='#') doesn't work. What's the reason for this? Does terminal or any other shell for that matter implicitly treat parameters differently for some reason? – winston the dog Apr 22 '19 at 02:55
  • Each `python -c` command will execute independently of any other. If you want to do both `a,b=1,2` and `print(a,b,sep='#')`, you have to put them in the same command. On my machine, `python3 -c "a,b=1,2;print(a,b,sep='#')"` produces the expected output of `1#2` – Green Cloak Guy Apr 22 '19 at 17:25