Which of these is the best practice for executable Linux scripts:

#! usr/bin/env python
#! usr/bin/python
#! usr/bin/env python3
#! usr/bin/python3

All four of them work just fine on my system, so I'm looking for the best practice. Thanks.

Edited 3 Years Ago by farmwife

There is a possibility that the python executable is not in /usr/bin on other people's systems. It could be in /usr/local/bin, /home/otheruser/.local/bin, or anywhere else. Without the env, you are telling it exactly which executable to use.

env will use the system's $PATH to determine where python is. There is also a possibility the env executable isn't really in /usr/bin, but that's a slim chance.

Long story short, if you are writing for only yourself and your machine, you can use whatever you want. I think it's a good practice to use #!/usr/bin/env python if you are distributing your scripts.

Edited 3 Years Ago by chriswelborn: added other location example

Thanks, Chris. Should I specify Python 3 or just let the user's system choose the version?

Also, someone suggested using the echo command for writing simple scripts in bash, like this:

echo '#! usr/bin/env python' >> script.py
echo 'print("This is a test.")' >> script.py
./script.py

It seems to be a low-mess way to write a very simple script. Do you ever use it?

You should specify python3 only if your code is written in python 3.

The bash trick is seldom useful. It is for people too lazy to open an editor to start a python script, or for bash programmers.

A more useful idea is to use a file template in your favorite editor. For example kde's kate editor has a file template plugin. It allows to define a default file to start editing a new python script in 1 click. For example you could use

#!/usr/bin/env python
#-*-coding: utf8-*-
from __future__ import unicode_literals, print_function, division

#== docstring ==========================================
__doc__ = """
"""

#== imports ============================================


if __name__ == "__main__":
    pass

Other editors (gedit, vim, emacs, ulipad...) have similar features.

Edited 3 Years Ago by Gribouillis

More newb questions. I was looking for some information and went to this webpage:

http://docs.python.org/2/library/stdtypes.html

There, I learned more than a hundred things I didn't know about Python before, but was not able to find what I was looking for, which is how to format this bit of bad code:

if int(input_value) == True:
    [do something]
else:
    [do something else]

The idea being to check whether the raw_input is the string equivalent of a valid integer or contains string or float values. Please tell me what I'm doing wrong.

Like often in python, the solution is to convert to integer and catch an exception if it fails

try:
    x = int(input_value)
except ValueError:
    pass # do something else
else:
    pass # do something

Edited 3 Years Ago by Gribouillis

should the "pass #" be rendered exactly that way or does the "#" stand for something else?

should the "pass #" be rendered exactly that way or does the "#" stand for something else?

pass is a do-nothing statement. The # is the beginning of a comment.

This works just fine:

x = raw_input('Type a number and hit enter: ')

try:
    x = int(x)
except ValueError:
    print("You didn't type a number!")
else:
    print('Thanks for typing a number!')

But when I try to create two functions that I can call repeatedly as part of a while statement so that they loop until the user does type a number, I get error messages coming out my ears. Grr.

Here is an example function

def int_input(prompt, error_msg):
    while True:
        x = raw_input(prompt)
        try:
            x = int(x)
        except ValueError:
            print(error_msg)
        else:
            return x

x = int_input("Type an integer and hit enter: ", "This was not an integer. Try again.")

Edited 3 Years Ago by Gribouillis

The function looks a lot like something that would be part of a standard library. Is it?

The function looks a lot like something that would be part of a standard library. Is it?

There are many potential fluctuations in the way a program can ask for an integer. A library can add many options to a function int_input() to cover most of the cases. The other possibility is to provide only lower level functions like raw_input().

Tony, I love the term "jail functions." The only thing I'd add to your code snippet is "Do you want to quit in frustration? (y/n)"--with a jail function requiring the correct input for that too, lol.

Grib, which libraries do you usually rely on for that?

Grib, which libraries do you usually rely on for that?

I don't usually need an integer from the user. External integers may come from command line at program invocation, or from a configuration file or perhaps a graphical user interface. If I really need console input, IĀ use raw_input().

For loops, I designed a raw_inputs() (notice the plural) which is an infinite sequence of user answers to the same question:

def raw_inputs(prompt):
    while True:
        yield raw_input(prompt)

# example usage

def int_input(prompt, error_msg):
    for ans in raw_inputs(prompt):
        try:
            return int(ans)
        except ValuError:
            print(error_msg)

I tested your snippet in my terminal and it works just as you said it would. Thanks for providing it to me to study.

This question has already been answered. Start a new discussion instead.