Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot pass an argument to python with "#!/usr/bin/env python"

I needed to have a directly executable python script, so i started the file with #!/usr/bin/env python. However, I also need unbuffered output, so i tried #!/usr/bin/env python -u, but that fails with python -u: no such file or directory.

I found out that #/usr/bin/python -u works, but I need it to get the python in PATH to support virtual env environments.

What are my options?

like image 421
Eskil Avatar asked Jul 22 '10 07:07

Eskil


People also ask

How do you pass an argument in Python?

The special syntax *args in function definitions in python is used to pass a variable number of arguments to a function. It is used to pass a non-key worded, variable-length argument list. The syntax is to use the symbol * to take in a variable number of arguments; by convention, it is often used with the word args.

What are the 4 types of arguments in Python?

5 Types of Arguments in Python Function Definition:positional arguments. arbitrary positional arguments. arbitrary keyword arguments.

What are the 3 types of arguments in Python?

Hence, we conclude that Python Function Arguments and its three types of arguments to functions. These are- default, keyword, and arbitrary arguments.

How do you pass a string with spaces in Python?

If you want to pass named string arguments containing spaces in between to the python script, you can simply put the text in double quotes.


2 Answers

In some environment, env doesn't split arguments. So your env is looking for python -u in your path. We can use sh to work around. Replace your shebang with the following code lines and everything will be fine.

#!/bin/sh ''''exec python -u -- "$0" ${1+"$@"} # ''' # vi: syntax=python 

p.s. we need not worry about the path to sh, right?

like image 104
Ade YU Avatar answered Oct 11 '22 15:10

Ade YU


It is better to use environment variable to enable this. See python doc : http://docs.python.org/2/using/cmdline.html

for your case:

export PYTHONUNBUFFERED=1 script.py 
like image 31
Larry Cai Avatar answered Oct 11 '22 15:10

Larry Cai