Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing arguments with wildcards to a Python script

I want to do something like this:

c:\data\> python myscript.py *.csv

and pass all of the .csv files in the directory to my python script (such that sys.argv contains ["file1.csv", "file2.csv"], etc.)

But sys.argv just receives ["*.csv"] indicating that the wildcard was not expanded, so this doesn't work.

I feel like there is a simple way to do this, but can't find it on Google. Any ideas?

like image 477
Kiv Avatar asked Jan 01 '09 23:01

Kiv


People also ask

How do you pass arguments to a python script?

In Python, arguments are passed to a script from the command line using the sys package. The argv member of sys ( sys.argv) will store all the information in the command line entry and can be accessed inside the Python script. Python’s getopt module can also be used to parse named arguments. Let’s go through some examples.

How do I pass a variable to a python script?

One approach is to parameterize some of the variables originally hard coded in the script, and pass them as arguments to your script. If you have only 1 or 2 arguments, you may find sys.argv is good enough since you can easily access the arguments by the index from argv list.

What is argument parsing in Python?

Argument Parsing in Python Python Server Side Programming Programming Every programming language has a feature to create scripts and run them from the terminal or being called by other programs. When running such scripts we often need to pass on arguments needed by the script for various functions to be executed inside the script.

How to print arguments in Python with command line parameters?

# Print arguments one by one print('First argument:', str(sys.argv[0])) print('Second argument:', str(sys.argv[1])) print('Third argument:', str(sys.argv[2])) print('Fourth argument:', str(sys.argv[3])) Then execute the above script with command line parameters. python script.py first 2 third 4.5 You will see the results like below.


2 Answers

You can use the glob module, that way you won't depend on the behavior of a particular shell (well, you still depend on the shell not expanding the arguments, but at least you can get this to happen in Unix by escaping the wildcards :-) ).

from glob import glob
filelist = glob('*.csv') #You can pass the sys.argv argument
like image 117
Vinko Vrsalovic Avatar answered Oct 13 '22 11:10

Vinko Vrsalovic


In Unix, the shell expands wildcards, so programs get the expanded list of filenames. Windows doesn't do this: the shell passes the wildcards directly to the program, which has to expand them itself.

Vinko is right: the glob module does the job:

import glob, sys

for arg in glob.glob(sys.argv[1]):
    print "Arg:", arg
like image 38
Ned Batchelder Avatar answered Oct 13 '22 11:10

Ned Batchelder