Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
访问python中的上一个bash命令_Python_Bash - Fatal编程技术网

访问python中的上一个bash命令

访问python中的上一个bash命令,python,bash,Python,Bash,我希望能够在脚本本身中记录用于运行当前python脚本的命令。例如,这是我尝试过的: #test.py import sys,subprocess with open('~/.bash_history','r') as f: for line in f.readlines(): continue with open('logfile','r') as f: f.write('the command you ran: %s'%line.strip('\n'))

我希望能够在脚本本身中记录用于运行当前python脚本的命令。例如,这是我尝试过的:

#test.py
import sys,subprocess
with open('~/.bash_history','r') as f:
    for line in f.readlines():
        continue

with open('logfile','r') as f:
    f.write('the command you ran: %s'%line.strip('\n'))
然而.bash_的历史似乎并不是按时间顺序排列的。为了便于记录,最好的推荐方法是什么?谢谢

更新:不幸的是,sys.argv并不能完全解决我的问题,因为我有时需要使用进程替换作为输入变量

e、 python test.py一个是使用。它将包含传递给脚本的参数列表

import sys

print 'Number of arguments:', len(sys.argv), 'arguments.'
print 'Argument List:', str(sys.argv)
示例输出:

>python test.py
Number of arguments: 1 arguments.
Argument List: ['test.py']

>python test.py -l ten
Number of arguments: 3 arguments.
Argument List: ['test.py', '-l', 'ten']

如您所见,
sys.argv
变量包含脚本的名称,然后是传递的每个单独参数。但是,它确实缺少了命令的
python
部分。

您想要做的事情并不是普遍可行的。正如devnull所说,bash中的历史文件并不是为每个键入的命令编写的。在某些情况下,它根本不被编写(用户设置
HISTFILESIZE=0
,或者使用不同的shell)

在调用python脚本之前很久,就会解析和处理键入的命令。因此,您的问题与python完全无关。您想做的事情是否可能完全取决于调用shell<代码>bash不提供您想要的内容


如果您可以控制调用方的shell,您可以尝试使用
zsh
。在那里,如果您
setopt INC_APPEND_HISTORY
,zsh将为每个键入的命令追加其历史文件,这样您就可以对历史文件进行解析。

并不是在每个命令之后都写入历史。
sys.argv
不是键入命令的完美副本,但它很接近。实际上,sys.argv并不完全满足我的需要,由于我在Linux上使用诸如python.test之类的进程替换时使用了输入参数,因此可能
/proc//cmdline
/proc//exe
,或者其他类似的东西可能会有所帮助,尽管它们可能会遇到与
sys.argv
类似的问题。。。当然,这不会捕获进程替换,因为这都是由shell处理的,并且适当的管道等都是在程序开始运行之前构建的……感谢您的建议。请参阅问题中的我的更新,了解sys.argv无法完全解决我的问题的原因。