Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set command alias for print in python?

Tags:

python

aliases

In bash you can give a command an alias like so:

alias e=echoset 
alias e="echo blah"

I want to know how to do the same thing in Python. I know you can give classes aliases, but when I try to give a command (the print statement for example) an alias, I get an error:

>>> p = print
  File "<stdin>", line 1
    p = print
            ^
SyntaxError: invalid syntax

I can do this:

p = "print"
exec(p)

But that isn't really the same thing as aliasing, and I can't give any input to the command.

Update: @atzz You guessed right, it is not specific to print. What I am trying to get to work is this:

This is supposed to set the command, but instead, it just beeps when I enter this:
>>> beep = Popen(['play', '-q', '/home/Username/Mich/Sound Effects/Beeps/beep-17-short.ogg'])

Then when I enter beep into the prompt, it shows this:
>>> beep <subprocess.Popen object at 0x9967b8c>

But other then this problem I have, at least now I know that you can't give statements aliases.

like image 348
DanielTA Avatar asked Aug 30 '12 06:08

DanielTA


2 Answers

Is your question specific to print?

In Python prior to 3.0, print is a keyword in the language grammar. Since it's not a first-class language object, you cannot assign it to a variable.

In Python 3.0, there is no keyword print; there's a print function instead (documentation).

With an appropriate future statement, you can use the print function in Python 2.6+:

from __future__ import print_function
a = print
a("Hello!")
like image 115
atzz Avatar answered Nov 14 '22 22:11

atzz


It's only the print statement you'll have this problem with, because it's a statement (like while/if/etc.) rather than a function.

If you wanted to 'rename' (for instance) len, it would work just fine.

like image 27
james.haggerty Avatar answered Nov 14 '22 23:11

james.haggerty