繁体   English   中英

Python:在linux终端中获取最后一个命令行

[英]Python: get last command line in linux terminal

我想编写一个 python 脚本来访问在终端中执行的最后一个命令,即启动程序的命令。

例如,如果我输入python myfile.py ,我希望终端输出“python myfile.py”

首先我试过:

    import os
    os.system("touch command.txt")
    os.system("history > command.txt")
    with open("command.txt", "r") as f:
        command = f.read()[-1]
    print(command)

但这不起作用,因为 history 是 bash 内置函数。

然后我试过:

    import os, subprocess
    command = subprocess.check_output(["tail","-n","1",os.path.expanduser("~/.bash_history")]).decode("utf-8").rstrip()
    print(command)

但这不符合我的期望,因为 bash 历史记录仅在终端关闭时更新。

为了改善这种行为,我尝试了os.putenv("PROMPT_COMMAND", "history-a") ,但它也没有帮助,因为 bash 历史更新仍然落后一步,因为我的变量命令现在只包含命令行在python myfile.py之前

现在我被困住了,我需要你的帮助

如果没有 shell 本身的参与,您无法以可靠的方式获取原始 shell 命令行,但您可以使用sys.argv生成等效的命令行。 (它不会包括重定向之类的东西,但是如果您只是从程序的现有副本内部重新执行,那么所有这些执行都将在您开始之前已经执行完毕,因此当您重新执行自己时新副本将继承其效果)。

所以:

#!/usr/bin/env python
import os.path, sys
try:
    from shlex import quote  # Python 3
except ImportError:
    from pipes import quote  # Python 2

sys_argv_str = ' '.join(quote(x) for x in sys.argv)

print("We can be restarted by calling the argv: %r" % (sys.argv,))
print("As a shell-syntax string, that would be: %s" % (sys_argv_str,))
print("...or, if your shell is bash, you can specify the interpreter directly:")
print('   ' + ' '.join(quote(x) for x in (['exec', '-a', sys.argv[0], os.path.abspath(sys.executable), os.path.abspath(__file__)] + sys.argv[1:])))

如果有人调用./yourprogram "first argument" "second argument" ,该输出可能如下所示:

We can be restarted by calling the argv: ['./yourprogram', 'first argument', 'second argument']
As a shell-syntax string, that would be: ./yourprogram 'first argument' 'second argument'
...or, if your shell is bash, you can specify the interpreter directly:
   exec -a ./yourprogram /usr/bin/python /home/charles/tmp/yourprogram 'first argument' 'second argument'

请注意,不能保证argv[0]__file__相同! 当一个程序启动另一个程序时,它可以在argv[0]槽中传递它喜欢的任何字符串; 这只是约定,而不是坚定的保证,其中将包含用于启动手头软件的名称。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM