简体   繁体   中英

python behaviour when passed an asterisk

I'm writing a small script, that should be able to handle multiple files. So I've added that files can be passed comma seperated, and do a arg.split(',') and then handle each one.

Now I've wanted to add asterisk as input possibility like

python myPythonScript.py -i folder/*

If I print the the argument to option -i right when I access it the first time I get

folder/firstFileInFolder.txt

But if I call my script with

python myPythonScript.py -i someFolder/someFile,folder/*

it works just fine. Does anyone have an idea, why python might behave that way?

Try to run this script

import sys

for arg in sys.argv:
    print arg

python script.py *

your shell expands the asterisk before python sees it.

As mentioned in the comments, your shell is expanding the asterisk for the non-comma separated case. If you know that the user may specify an asterisk as part of a file name as in your second example, you can have Python do the path expansion by using the glob module.

from glob import glob
glob('*')

code which would allow either the shell or Python to do asterisk expansion may look something like this:

import glob
file_list = []
for pattern in sys.argv[1:]:
    file_list.extend(glob.glob(pattern))

In your case, using a comma as a separator would then prevent you from using a comma as part of a filename.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM