0

I am trying to put in my Bash script a one-liner that would print my python's path

python -c 'import sys; for p in sys.path: print(p)'

the for keyword is flagged as an invalid syntax

I was expecting that the semicolon would work as a new line character, yet it disappointed me.

1

2 Answers 2

6

you didn't ask a question, but you are looking for:

python -c 'import sys; print("\n".join(sys.path))'

The reason your posted example doesn't work is that block-introducing statements must be the first statement on the physical line (meaning they can't appear after a semicolon). (More specifically: semicolons can only be used to separate "simple statements"; compound statements cannot be introduced as part of a semicolon-separated group of statements.)

If you're using BASH to run the command, you actually have a second option:

python -c $'import sys\nfor p in sys.path: print(p)'

The $'...' in BASH evaluates ANSI-C backslash escape sequences (such as \n for a newline), thus allowing you to put the for statement on a new physical line.

Sign up to request clarification or add additional context in comments.

3 Comments

Your answer would be better if it actually explained why your version works while the OP's does not.
@jarmod thanks; added explanation and a second option when running BASH.
Note: While not technically a one-liner, you could just put a literal newline in a quoted command, e.g. python -c 'import sys on the first line, and because the ' wasn't paired, you can continue, entering for p in sys.path: print(p)' on the second line. Doesn't rely on bash-specific functionality like $'', and while technically not a one-liner, when we're talking about scripting languages, "one-liner" often just means "putting a whole script in the command line", which this does.
4

Other method is to unpack all values in print and use new line as separator

python -c 'import sys; print(*sys.path, sep="\n")'

I'm not sure but print() may have limit to 255 arguments (or maybe it had it in older versions)
but sys.path is shorter.


After ; one-liner doesn't allow for some constructions which normally need indentations, like for-loop, while-loop, if/elif/else, try/except

2 Comments

There's no meaningful limit on number of arguments to print that would apply here (there might be some upper limit, can't be bothered to check source code, but it's well beyond what you'd reasonably print as a single call, I've tested to 10M). Some older versions had limits on number of fixed arguments IIRC, but those limits never applied to *-unpacked varargs to my knowledge.
This is very helpful. I would like to hear more about the restrictions placed on expressions after ;.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.