linux 如何在python中编写find和exec命令

cwxwcias  于 2023-01-08  发布在  Linux
关注(0)|答案(5)|浏览(181)

我有一个shell脚本
第一个月
它在特定的目录中查找所有的JSON文件,并执行我拥有的其他Python脚本。
我怎样才能做这个python脚本?

ycl3bljg

ycl3bljg1#

我不确定我是否理解了你的问题,如果你试图从python脚本执行shell命令,你可以使用os.system():

import os
os.system('ls -l')

完整文件

qhhrdooz

qhhrdooz2#

import glob,subprocess
for json_file in glob.glob("/home/tmp/*.json"):
    subprocess.Popen(["python","/path/to/my.py",json_file],env=os.environ).communicate()
sqxo8psd

sqxo8psd3#

如果你想使用Python而不是find,那么从os.walk(官方文档)开始获取文件,一旦你有了它们(或者当你有了它们的时候),就可以按照你喜欢的方式操作它们。
从该页面:

import os

for dirName, subdirList, fileList in os.walk(rootDir):
    print('Found directory: %s' % dirName)
    for fname in fileList:
        print('\t%s' % fname)
        # act on the file
ruoxqz4g

ruoxqz4g4#

我猜你想调整你的另一个python文件/python/path/script.py,这样你只需要这一个文件:

#!/usr/bin/env python
import sys
import glob
import os

#
# parse the command line arguemnts
#
for i, n in enumerate(sys.argv):
    # Debug output
    print "arg nr %02i: %s" % (i, n)

    # Store the args in variables
    # (0 is the filename of the script itself)
    if i==1:
        path = sys.argv[1] # the 1st arg is the path like "/tmp/test"
    if i==2:
        pattern = sys.argv[2] # a pattern to match for, like "'*.json'"

#
# merge path and pattern
# os.path makes it win / linux compatible ( / vs \ ...) and other stuff
#
fqps = os.path.join(path, pattern)

#
# Do something with your files
#
for filename in glob.glob(fqps):
    print filename

    # Do your stuff here with one file        
    with open(filename, 'r') as f:  # 'r'= only ready from file ('w' = write)
        lines = f.readlines()
    # at this point, the file is closed again!
    for line in lines:
        print line
        # and so on ...

然后,您可以使用/python/path/script.py /tmp/test/ '*.json'这样的脚本(由于第一行名为shebang,因此无需在前面编写python,但您需要使用chmod +x /python/path/script.py使其可执行一次)
当然,您可以省略第二个arg并为pattern指定默认值,或者一开始只使用一个arg,我这样做是为了演示os.path.join()和不应该由bash扩展的参数的引用(比较在开头打印的参数列表上使用'*.json'*.json的效果)
Here是一些关于处理命令行参数的更好/更复杂方法的信息。
而且,作为一个额外的好处,using a main() function也是可取的,如果你的脚本变得更大或者正在被其他python脚本使用,可以保持概览。

8qgya5xd

8qgya5xd5#

你需要的是

find /tmp/test/* -name "*.json" -exec sh -c "python /python/path {}" \;

相关问题