Using conditional expression in python -c interpreter

I am trying to figure out how to pass the following conditional statement to the python (-c) interpreter command command.

if sys.maxsize > 2**32:
    print '64'
else:
    print '32'

64

However, I constantly get syntax errors, such as:

>python -c "import sys; if sys.maxsize > 2**32: print '64' else: print '32';"
  File "<string>", line 1
    import sys; if sys.maxsize > 2**32: print '64' else: print '32';
                 ^
SyntaxError: invalid syntax

It was surprisingly hard for me to find a good example of this use. I must be missing something here ...

+5
source share
3 answers

After a (very) brief search, I cannot find this documented anywhere, but it seems that it -cstrictly accepts the expression (i.e. something that may appear in the RHS assignment), not the statement. To get around this in your case, you need to do two things:

  • ( - ),
  • a if b else c

:

lvc@tiamat:~$ python -c "from __future__ import print_function; import sys; print('64' if sys.maxsize > 2**32 else '32')"
64
+5

, ( Python 2.7):

> python -c 'import sys; print 64 if sys.maxsize > 2**32 else 32'
64

: Python ?

+4

You can use multiple lines (at least in bash):

$ python -c "import sys
> if sys.maxsize > 2**32:
>  print '64'
> else:
>  print '32'"
64

To get all the platform information, you can:

$ python -mplatform

Or just architecture:

$ python -c "import platform; print platform.architecture()"
('64bit', 'ELF')
+1
source

All Articles