【问题标题】:python use of ack in combination with tkinterpython 结合 tkinter 使用 ack
【发布时间】:2016-09-02 19:00:08
【问题描述】:

我有点卡住了。我想在目录中“确认”并在终端中打印确认列表。但是当我尝试运行我的脚本时,它只在当前目录中确认。

我使用 tkinter 创建 tkFileDialog.askdirectory()

但是,我还是卡住了..

有人可以帮忙吗?或指出我做错了什么? 我写的代码如下

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"

【问题讨论】:

  • 考虑使用os.walk 遍历目录树。

标签: python printing tkinter directory ack


【解决方案1】:

两种选择:

  1. 运行ack前跳转到目标目录

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

注意:这种方法被一些人认为是一种反模式(参见下面 zwol 的评论),因为它可能无法返回到原始目录(例如,如果它已被删除或它的权限已更改)并且os.chdir 会影响整个进程,因此可能会中断其他线程中正在进行的工作。

  1. 将目标文件夹添加到ack命令中

    os.system("ack -i 'password' --ignore-file=is:easyack.py {0}".format(foldername))
    

【讨论】:

  • 你的 (1) 是反模式;可能无法返回origin,而且 cwd 是一个进程范围的设置,因此更改它可能会破坏其他线程中正在进行的并发工作。
  • 谢谢!生病尝试他们两个!再次感谢您的宝贵时间!我会尽快回复你如果我让它工作!
  • @NoFxor:不客气。 zwol 关于优先使用子进程模块而不是使用 os.system() 确实是正确的。你愿意标记答案吗?很高兴我能帮上忙。
【解决方案2】:

您需要指示ack 子进程在foldername 而不是当前目录中运行。你不能用os.system 做到这一点,但你可以用subprocess 模块,使用Popencwd= 参数或任何便利包装器。在这种情况下,subprocess.check_call 就是您想要的:

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

我强烈建议你忘记你曾经听说过os.system 并一直使用subprocess。对于非常简单的事情,它会稍微复杂一些,但它能够处理比os.system 更复杂的事情。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-25
    • 1970-01-01
    • 2017-10-11
    • 2015-11-27
    • 2015-04-27
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多