direct execution of python scripts Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of direct execution of python scripts without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I have noticed that sometimes python scripts are not being started directly, ie /foo/bar.py, but rather from a shell script, which does nothing else than /usr/bin/python -O /foo/bar.py $@

One such example is wicd network manager. /usr/bin/wicd-gtk is a shell script, which starts the wicd-client.py:

$ cat /usr/bin/wicd-gtk

exec /usr/bin/python -O /usr/share/wicd/gtk/wicd-client.py $@

What is the purpose of this extra step?

What would be the difference if I started /usr/share/wicd/gtk/wicd-client.py directly (provided it is executable) ?

Answer

You didn’t post the full script — the script does other things before running wicd-client.py. It first ensures that a certain directory and a certain symbolic link exist:

# check_firstrun()
if [ ! -d "$HOME/.wicd" ]; then
    mkdir -p "$HOME/.wicd"
fi
# Make sure the user knows WHEREAREMYFILES ;-)
if [ -e "/var/lib/wicd/WHEREAREMYFILES" ] && [ ! -L "$HOME/.wicd/WHEREAREMYFILES" ]; then
    ln -s "/var/lib/wicd/WHEREAREMYFILES" "$HOME/.wicd/WHEREAREMYFILES"
fi

Then it runs Python with the -O option, which causes it to optimize the bytecode. I don’t know how useful that is.

The wrapper script also forces /usr/bin/python to be used, whereas /usr/share/wicd/gtk/wicd-client.py starts with #!/usr/bin/env python, so it picks up whichever python comes first in the command search path. On most systems this won’t make any difference.

Note that there’s a bug in this script: $@ should be "$@". The wrapper script will fail if any argument contains whitespace or wildcard characters [*?.

You could safely run /usr/share/wicd/gtk/wicd-client.py manually, as long as ~/.wicd exists. The Debian package doesn’t make it executable, though; maybe other distributions do.

We are here to answer your question about direct execution of python scripts - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji