【问题标题】:How to delete bash history in python script on Mac?如何在 Mac 上的 python 脚本中删除 bash 历史记录?
【发布时间】:2014-02-02 07:03:17
【问题描述】:

我想在我的 Macbook Pro 上使用 python 脚本删除 bash 历史记录。

我知道两种使用 bash shell 删除 bash 历史记录的方法

1.rm ~/.bash_history

2.历史-c

但是这些命令在带有子进程的 python 脚本中不起作用:

1.rm ~/.bash_history

import subprocess
subprocess.call([‘rm’, ‘~/.bash_history'])

错误:

rm: ~/.bash_history: 没有这样的文件或目录

2.历史-c

import subprocess
subprocess.call(['history', '-c'])

错误:

文件“test.py”,第 8 行,在 subprocess.call(['history', '-c']) 文件“/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py”,行>524,在调用中 返回 Popen(*popenargs, **kwargs).wait() init 中的文件“/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py”,>711 行 读错,写错) 文件“/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py”,行>1308,在_execute_child 引发 child_exception

有什么想法吗?

【问题讨论】:

    标签: python macos bash history delete-file


    【解决方案1】:

    你有两个问题:

    首先python看不懂~,需要扩展一下:

    subprocess.call(['rm', os.path.expanduser('~/.bash_history')])
    

    其次,history 是一个内置的 shell。使用 shell 调用它:

    subprocess.call(['bash', '-c', 'history -c'])
    

    【讨论】:

    • 您好,感谢您的回复。我已经尝试过代码。 'subprocess.call(['rm', os.path.expanduser('~/.bash_history')])' 效果很好! subprocess.call(['bash', '-c', 'history -c'])
    • 但是 subprocess.call(['bash', '-c', 'history -c']) 不起作用....我试图将评论编辑为一个好的格式,但是系统告诉我“评论只能在 5 分钟内编辑”。这是我第一次编辑评论,我很抱歉让它难以阅读。 @devnull
    • @Matt history -c删除$HOME/.bash_history。它只是清除当前会话中的历史列表。从终端尝试说:history -c,然后是cat ~/.bash_history,你应该能够理解。你也可以试试history -w,然后是history -c
    • @Matt 简而言之,删除文件是您可能要考虑的选项。此外,如果您不希望bashhistory 记录到文件中,您可以在~/.bashrc 中包含export HISTFILE=/dev/null 行。
    • 而subprocess.call(['rm', os.path.expanduser('~/.bash_history')]) 可以删除文件。但是当我在 shell 中运行“历史”时,我仍然可以看到命令历史。很抱歉,问题仍未解决。
    猜你喜欢
    • 2016-10-05
    • 2020-09-11
    • 2015-06-23
    • 1970-01-01
    • 1970-01-01
    • 2021-11-14
    • 1970-01-01
    • 2011-02-10
    • 1970-01-01
    相关资源
    最近更新 更多