python 将 ack 与 tkinter 结合使用
python use of ack in combination with tkinter
我有点卡住了。我想在目录中 "ack" 并在终端中打印确认列表。但是当我尝试 运行 我的脚本时,它只在当前目录中确认。
我正在使用 tkinter 创建 tkFileDialog.askdirectory()
然而,我还是卡住了..
有人可以帮忙吗?或者指出我做错了什么?
我写的代码如下
foldername = tkFileDialog.askdirectory()
if os.path.isdir(foldername):
print "3[1m" + foldername + "3[0m"
os.system("ack -i 'password' --ignore-file=is:easyack.py")
else: print "3[1m" + "No folder chosen" + "3[0m"
两个选项:
在运行ack
之前跳转到目标目录
origin = os.getcwd()
if os.path.isdir(foldername):
os.chdir(foldername)
print(..., etc.)
os.chdir(origin)
注意:这种方法被一些人认为是一种反模式(参见下面 zwol 的评论),因为它可能无法返回到原始目录(例如,如果它已被删除或其权限已更改) 和 os.chdir 影响整个进程,因此可能会中断其他线程中正在进行的工作。
将目标文件夹添加到ack命令
os.system("ack -i 'password' --ignore-file=is:easyack.py {0}".format(foldername))
您需要指示 ack
子进程到 foldername
中的 运行 而不是当前目录。你不能用 os.system
做到这一点,但你可以用 subprocess
模块,使用 Popen
的 cwd=
参数或任何方便的包装器。在这种情况下,subprocess.check_call
就是您想要的:
if os.path.isdir(foldername):
#print "3[1m" + foldername + "3[0m"
sys.stdout.write("3[1m{}3[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 "3[1m" + "No folder chosen" + "3[0m"
sys.stdout.write("3[1m{}3[0m is not a folder\n"
.format(repr(foldername)[1:-1]))
我强烈建议你忘记你听说过 os.system
并一直使用 subprocess
。对于非常简单的事情来说它有点复杂,但是它能够处理比 os.system
.
更复杂的事情。
我有点卡住了。我想在目录中 "ack" 并在终端中打印确认列表。但是当我尝试 运行 我的脚本时,它只在当前目录中确认。
我正在使用 tkinter 创建 tkFileDialog.askdirectory()
然而,我还是卡住了..
有人可以帮忙吗?或者指出我做错了什么? 我写的代码如下
foldername = tkFileDialog.askdirectory()
if os.path.isdir(foldername):
print "3[1m" + foldername + "3[0m"
os.system("ack -i 'password' --ignore-file=is:easyack.py")
else: print "3[1m" + "No folder chosen" + "3[0m"
两个选项:
在运行ack
之前跳转到目标目录origin = os.getcwd() if os.path.isdir(foldername): os.chdir(foldername) print(..., etc.) os.chdir(origin)
注意:这种方法被一些人认为是一种反模式(参见下面 zwol 的评论),因为它可能无法返回到原始目录(例如,如果它已被删除或其权限已更改) 和 os.chdir 影响整个进程,因此可能会中断其他线程中正在进行的工作。
将目标文件夹添加到ack命令
os.system("ack -i 'password' --ignore-file=is:easyack.py {0}".format(foldername))
您需要指示 ack
子进程到 foldername
中的 运行 而不是当前目录。你不能用 os.system
做到这一点,但你可以用 subprocess
模块,使用 Popen
的 cwd=
参数或任何方便的包装器。在这种情况下,subprocess.check_call
就是您想要的:
if os.path.isdir(foldername):
#print "3[1m" + foldername + "3[0m"
sys.stdout.write("3[1m{}3[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 "3[1m" + "No folder chosen" + "3[0m"
sys.stdout.write("3[1m{}3[0m is not a folder\n"
.format(repr(foldername)[1:-1]))
我强烈建议你忘记你听说过 os.system
并一直使用 subprocess
。对于非常简单的事情来说它有点复杂,但是它能够处理比 os.system
.