use*_*908 2 python unix find argparse
我有一个可以使用UNIX'find'命令获得的文件列表,例如:
$ find . -name "*.txt"
foo/foo.txt
bar/bar.txt
Run Code Online (Sandbox Code Playgroud)
如何将此输出传递给像hello.py这样的Python脚本,以便我可以使用Python的argparse库解析它?
谢谢!
用途xargs:
find . -name "*.txt" | xargs python -c 'import sys; print sys.argv[1:]'
Run Code Online (Sandbox Code Playgroud)
如果只想输出文本find(1),那么使用管道:
~$ find . -name "*.txt" | python hello.py
Run Code Online (Sandbox Code Playgroud)
如果要将文件列表作为参数传递给脚本,请使用xargs(1):
~$ find . -name "*.txt" -print0 | xargs -0 python hello.py
Run Code Online (Sandbox Code Playgroud)
或使用-exec选项find(1).
从man find:
-exec command ;\n Execute command; true if 0 status is returned. All following\n arguments to find are taken to be arguments to the command until\n an argument consisting of `;\' is encountered. The string `{}\'\n is replaced by the current file name being processed everywhere\n it occurs in the arguments to the command, not just in arguments\n where it is alone, as in some versions of find. Both of these\n constructions might need to be escaped (with a `\\\') or quoted to\n protect them from expansion by the shell. See the EXAMPLES sec\xe2\x80\x90\n tion for examples of the use of the -exec option. The specified\n command is run once for each matched file. The command is exe\xe2\x80\x90\n cuted in the starting directory. There are unavoidable secu\xe2\x80\x90\n rity problems surrounding use of the -exec action; you should\n use the -execdir option instead.\n\n-exec command {} +\n This variant of the -exec action runs the specified command on\n the selected files, but the command line is built by appending\n each selected file name at the end; the total number of invoca\xe2\x80\x90\n tions of the command will be much less than the number of\n matched files. The command line is built in much the same way\n that xargs builds its command lines. Only one instance of `{}\'\n is allowed within the command. The command is executed in the\n starting directory.\nRun Code Online (Sandbox Code Playgroud)\n\n所以你可以做
\n\n find . -name "*.txt" -exec python myscript.py {} +\nRun Code Online (Sandbox Code Playgroud)\n