Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a conditional in the python interpreter -c command

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

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

64

However, I continually get syntax errors, such as the following:

>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

I found it surprisingly difficult to find a good example of this usage. I must be missing something big here...

like image 978
kevinmm Avatar asked Jul 31 '12 11:07

kevinmm


People also ask

What is interpreter in Python with example?

You write your Python code in a text file with a name like hello.py . How does that code Run? There is program installed on your computer named "python3" or "python", and its job is looking at and running your Python code. This type of program is called an "interpreter".

What is an if clause in Python?

In a Python program, the if statement is how you perform this sort of decision-making. It allows for conditional execution of a statement or group of statements based on the value of an expression.


1 Answers

After a (very) brief search, I can't find this documented anywhere, but it seems that -c strictly takes an expression (ie, something that can appear on the RHS of an assignment), not a statement. To get around this in your case, you need to do two things:

  1. Use the print function (function calls are an expression) rather than the print statement
  2. Use Python's a if b else c conditional expression

This gives you:

lvc@tiamat:~$ python -c "from __future__ import print_function; import sys; print('64' if sys.maxsize > 2**32 else '32')"
64
like image 83
lvc Avatar answered Sep 20 '22 02:09

lvc