开发者

xargs, python, reading files from stdin

开发者 https://www.devze.com 2023-02-28 17:03 出处:网络
In a directory with 30 CSV files, running: find . -name \"*.csv\" | (xargspython ~/script.py) How can I have python properly run on each file passed by xargs? I do print sys.stdin and it\'s just on

In a directory with 30 CSV files, running:

find . -name "*.csv" | (xargs  python ~/script.py)

How can I have python properly run on each file passed by xargs? I do print sys.stdin and it's just one file. I try for file in stdin loop, but开发者_开发知识库 there's nothing there. What am I missing?


In fact xargs does not pass to stdin. It passes all its read from stdin as arguments to the command you give it in parameter.

You can debug your command invokation with an echo:

find . -name "*.csv" | (xargs echo python ./script.py)

You will see all your files outputed on one line.

So in fact to access your files from arguments list in python use this in your script:

import sys
for argument in sys.argv[1:]:
    print argument


script.py is being run exactly once for each csv file

python ~/script.py file1.csv
python ~/script.py file2.csv
python ~/script.py file3.csv
python ~/script.py file4.csv

etc

If you want to run it like

python ~/script.py file1.csv file2.csv file3.csv

then do

python ~/script.py `find . -name "*.csv"`

or

python ~/script.py `ls *.csv`

(the " may have to be escaped, not sure)

EDIT: note the difference between ` and '

0

精彩评论

暂无评论...
验证码 换一张
取 消