OS X 및 Ubuntu에서 실시간으로 파일 시스템보기


11

디렉토리를보고 실시간으로 변경되는 파일 이름을 뱉어내는 CLI 도구를 찾고 있습니다.

some_watch_command /path/to/some/folder | xargs some_callback

나는 inotify( inotify-tools?)을 알고 있으며 필요한 것 같지만 Linux (내 경우에는 우분투)와 OSX와 호환되는 것이 필요합니다.

번개를 맞을 필요는 없지만 변경시 트리거해야합니다 (1 초 이내에 합리적 임). 또한 위에서 언급 한 정확한 CLI 프로그램이 반드시 필요한 것은 아닙니다. 일부 기본 기술이 존재하고 두 플랫폼 모두에서 쉽게 스크립팅 할 수 있다면 좋을 것입니다.


1
같은 I fswatch- 내가 중복으로 태그 된 문제에 발견 OS X에 대한 superuser.com/questions/445907/...
— CWD

답변:


11

OS X은 일반적 으로이 작업에 폴더 작업 또는 시작 을 사용합니다.

내가 아는 유일한 크로스 플랫폼 툴 은 파이썬 용 워치 독 API 입니다 (따라서 OS X 및 Linux에서 사용 가능). 통해 설치 pip(또는 easy_install)

pip install watchdog

watchmedo시스템 이벤트에서 쉘 명령을 실행할 수 있는 명령 행 도구 와 함께 제공됩니다 . 다음과 같이 일반적인 구문을 확인하십시오.watchmedo --help

다음은 명령과 경로를 굵게 강조 표시하여 쉽게 수정할 수있는 간단한 예입니다.

watchmedo 쉘 명령
    -재귀
    --command = ' echo "$ {watch_src_path}" '\
     / some / folder

이것은 단순히 변경된 모든 파일이나 폴더의 경로를 뱉어 내고 watchmedo출력을 다른 쉘 명령 으로 파이프 할 수있게합니다 .


폴더 작업에는 일부 제한이 있으며 OSX 없이는 테스트하기가 어렵지만 watchmedo완벽하게 작동합니다. 감사!
— Adrian Schneider

2

내가 찾은 루비 스크립트를 조정하여 원하는 것을 정확하게 수행했습니다. 루비 코드는 다음과 같습니다.

#!/usr/bin/ruby
# Inspired by http://vikhyat.net/code/snippets/#watchfile

# How to use:
# This script takes two paramaters:  a folder and a shell command
# The script watches for when files in the folder are changed.  When they are, the shell command executes
# Here are some shortcuts you can put in the shell script:
# %F = filename (with extension)
# %B = base filename (without extension)


unless ARGV.length == 2
  puts "\e[32m    Usage: \e[0mruby OnSaveFolder.rb 'folder' 'command'"
  exit
end

require 'digest/md5'
require 'ftools'

$md5 = ''
$directory = File.expand_path(ARGV[0])
$contents = `ls #{$directory}`
$contentsList = $contents.split("\n")
$fileList = []


Dir.chdir($directory)

for i in $contentsList
  if ( File.file?(File.expand_path(i)) == true)
    $fileList.push(i)
  end
end

$processes = []

def watch(file, timeout, &cb)
  $md5 = Digest::MD5.hexdigest(File.read(file))
  loop do
    sleep timeout
    if ( temp = Digest::MD5.hexdigest(File.read(file)) ) != $md5
      $md5 = temp
      cb.call(file)
    end
  end
end

puts "\e[31m Watching files in folder \e[34m #{$directory}"
puts "\e[32m    Press Control+C to stop \e[0m"

for i in $fileList
  pid = fork do
    $num = 0
    $filePath = File.expand_path(i)

    watch i, 1 do |file|
      puts "\n     #{i} saved"

      $command = ARGV[1].dup
      if ( ARGV[1].include?('%F') )
        $command = $command.gsub!('%F', i)
      end
      if ( ARGV[1].include?('%B') )
        $command = $command.gsub!('%B', File.basename(i, '.*'))
      end

      $output = `#{$command}`
      if ( $output != '')
        puts "\e[34m     #{$command}\e[31m output: \e[0m"
        puts $output
      end
      puts "\e[34m     #{$command}\e[31m finished \e[0m (#{$num}, #{Time.now})\n"
      $num += 1

    end
  end
  $processes.push(pid)
end

Process.wait(pid)

for i in $processes
  `kill #{i}`
end

이 스크립트의 이름을 "OnSaveFolder.rb"로 지정했습니다. 변경 사항을 감시하려는 폴더와 변경이있을 때 실행할 bash 코드의 두 가지 매개 변수가 필요합니다. 예를 들어

ruby OnSaveFolder.rb '/home/Movies' 'echo "A movie has been changed!"'

이게 도움이 되길 바란다! 루비가 이런 유형의 작업에 매우 효과적이며 OS X에 기본적으로 설치되어 있습니다.


루비 배경없이 조정하기는 쉽지만 약간의 샷을 제공하십시오. 어쨌든 고마워!
— Adrian Schneider 2016 년

이것은 대단하다. 아래 폴더를 재귀 적으로 감시하는 방법을 알고 있습니까?
— Nate Flink

변경시 명령 실행에 신경 쓰지 않는다면 다중 플랫폼입니까, 아니면 유닉스입니까? 그리고 실제로 실시간입니까? 일부 파일 감시자에게는 말도 안되는 지연 시간 (분)이 있습니다.
— Automatico

2

당신은 넣을 수 lsof에 watch명령과 그 모든 업데이트 한 <s>초 :

watch -n <s> lsof

pid1, pid2, pid3 시청 및 pid4 무시와 같은 필터를 사용하여 시작하십시오.

lsof -p "pid1,pid2,pid3,^pid4"

충분하지 않으면 언제든지 grep을 사용하여 자체 필터를 작성할 수 있습니다.

OS X의 경우이 질문 의 답변을 참조하십시오 .


0

엔트 르 가 좋다. 보고자하는 정확한 파일을 이와 같이 필터링 할 수 있습니다.

find . -name '*.py' | entr python runTests.py

디렉토리 내의 특정 파일 만 모니터하려는 경우,보고자 find하는 파일 만 리턴하도록 명령 을 작성할 수 있습니다 .

보다 구성하는 것이 더 쉽다는 것을 알았습니다 fswatch.

당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.