0

Im kinda stuck. i want to "ack" in a directory and print the list of the ack in the terminal. but when i try to run my script it only ack's in the current directory.

im using tkinter to create the tkFileDialog.askdirectory()

however, im still stuck..

is there someone that can help out? or point out what im doing wrong? the code i wrote is below

foldername = tkFileDialog.askdirectory()

if os.path.isdir(foldername):
        print "\033[1m" + foldername + "\033[0m"
        os.system("ack -i 'password' --ignore-file=is:easyack.py")
else: print "\033[1m" + "No folder chosen" + "\033[0m"
NoFxor
  • 19
  • 1
  • 8

2 Answers2

2

Two options:

  1. Jump to the target directory before running ack

    origin = os.getcwd()
    if os.path.isdir(foldername):
        os.chdir(foldername)
        print(..., etc.)
    os.chdir(origin)
    

NOTE: This approach is considered an anti-pattern by some (see zwol's comment below) since it may not be possible to get back to the original directory (eg., if it has been removed or its permissions have changed) and os.chdir affects the whole process and therefore could disrupt work going on in other threads.

  1. Add the target folder to the ack command

    os.system("ack -i 'password' --ignore-file=is:easyack.py {0}".format(foldername))
    
Tom Barron
  • 1,554
  • 18
  • 23
  • Your (1) is an antipattern; it may be impossible to return to `origin`, and the cwd is a process-wide setting, so changing it can disrupt concurrent work being done in other threads. – zwol May 07 '16 at 21:28
  • Thank you! ill try both of them! thank you again for your time! ill get back to you a.s.a.p. if i got it working! – NoFxor May 07 '16 at 21:35
  • @NoFxor: You're welcome. zwol is really correct about preferring the subprocess module over using os.system(). Would you care to mark an answer? Glad I could help. – Tom Barron May 07 '16 at 21:41
1

You need to instruct the ack subprocess to run in foldername instead of the current directory. You can't do that with os.system but you can with the subprocess module, using the cwd= argument to Popen or any of the convenience wrappers. In this case, subprocess.check_call is what you want:

if os.path.isdir(foldername):
    #print "\033[1m" + foldername + "\033[0m"
    sys.stdout.write("\033[1m{}\033[0m\n".format(repr(foldername)[1:-1]))
    #os.system("ack -i 'password' --ignore-file=is:easyack.py")
    subprocess.check_call(
        ["ack", "-i", "password", "--ignore-file=is:easyack.py"],
        cwd=foldername)
else:
    #print "\033[1m" + "No folder chosen" + "\033[0m"
    sys.stdout.write("\033[1m{}\033[0m is not a folder\n"
                     .format(repr(foldername)[1:-1]))

I strongly advise you forget you ever heard of os.system and use subprocess all the time. It is a little more complicated for very simple things, but it's capable of much more complicated things than are possible with os.system.

zwol
  • 135,547
  • 38
  • 252
  • 361