Search code examples
pythonaliases

Set command alias for print in python?


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.


Solution

  • To answer your new question, if you want to do this and have beep execute later:

    beep = Popen(['play', '-q', '/home/Username/Mich/Sound Effects/Beeps/beep-17-short.ogg'])
    

    Change it to:

    beep = lambda: Popen(['play', '-q', '/home/Username/Mich/Sound Effects/Beeps/beep-17-short.ogg'])
    

    Or just a function :-)

    def beep(): Popen(['play', '-q', '/home/Username/Mich/Sound Effects/Beeps/beep-17-short.ogg'])
    

    Otherwise 'beep' will just hold the return value of Popen.