简体   繁体   English

如何在 python 中编写查找和执行命令

[英]How can I write find and exec command in python

I have a shell script that does我有一个 shell 脚本

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

it looks for all the JSON files in specific directories and executes the OTHER python script that I have..它在特定目录中查找所有 JSON 文件并执行我拥有的其他 python 脚本..

How can I do this python scripting?我该如何编写这个 python 脚本?

I'm not sure if I understood your question, if you are trying to execute a shell command from a python script, you can use os.system() : 我不确定是否理解您的问题,如果您尝试从python脚本执行shell命令,则可以使用os.system():

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

complete documentation 完整的文件

If you want to use Python instead of find, start with os.walk ( official doc ) to get the files. 如果要使用Python而不是find,请从os.walk官方doc )开始获取文件。 Once you have them (or as you them), act on them however you like. 一旦有了它们(或与它们一样),就可以根据自己的喜好对它们进行操作。

From that page: 从该页面:

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
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()

I guess you want to adjust your other python file /python/path/script.py , such that you only need this one file: 我想您想调整其他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 ...

Then you can use the one script like this /python/path/script.py /tmp/test/ '*.json' . 然后,您可以使用像/python/path/script.py /tmp/test/ '*.json'这样的一个脚本。 (Without needing to write python in front, thanks to the very first line, called shebang. But you need to make it executable once, using chmod +x /python/path/script.py ) (由于第一行称为shebang,因此无需在前面编写python 。但是您需要使用chmod +x /python/path/script.py使它一次可执行。)

Of course you can omit the 2nd arg and assign a default value to pattern, or only use one arg in the first place. 当然,您可以省略第二个arg并为pattern指定默认值,或者仅使用一个arg。 I did it this way to demonstrate os.path.join() and quoting of arguments that should not be extended by bash (compare the effect of using '*.json' and *.json on the printed list of arguments at the start) 我这样做是为了演示os.path.join()并引用bash不应该扩展的参数(比较开始时在打印的参数列表上使用'*.json'*.json的效果)

Here are some information about better / more sophisticated ways of handling command line arguments. 这里是有关处理命令行参数的更好/更复杂方法的一些信息。

And, as a bonus, using a main() function is advisable as well, to keep overview if your script gets larger or is being used by other python scripts. 另外,建议您同时使用main()函数 ,以在脚本变大或被其他python脚本使用时保持概览。

What you need is你需要的是

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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