How to avoid python argv refer to file in the system

Viewed 23

I tried to do some work that need to deal with python's argv in linux.

The command called shall be something like python test.py export file xxx.json, and I could use argv[4] as file_name. And here if I just write * as file_name, it would be the first file in the current directory.

How can I avoid this kind of error? argv[4] == '*' will return false.

1 Answers

Quote the asterisk when starting your program:

python test.py export file "*"

Btw, it is not python that is extending the asterisk but it is your shell when you call the program. The python program will get in its argv list all files in your current directory.

As others commented, expecting a literal "*" as argument for your programs is bad practice, better to use a flag. Check the argparse module how to make proper command line interfaces.

Related