Python subprocess.call 一个 bash 别名
问题描述
在工作中有一个列出已完成任务的脚本.这是由其他人编写的,并通过网络托管.我的 .bashrc 中有一个别名,它调用这个脚本,它有很多标志等,我想编写一个 python 脚本,每隔几分钟调用一次这个别名,这样我就可以打开一个带有更新统计信息的 shell.但是,subprocess.call("myAlias")
失败.我对 python 还是很陌生,并且正在努力解决这个问题.
At work there's a script that lists completed tasks. This was written by someone else and is hosted over the network. I have an alias in my .bashrc that calls this script, with its many flags and such, and I wanted to write a python script that would call this alias every few minutes so I can have a shell open with updated stats. However, subprocess.call("myAlias")
fails. I'm still fairly new to python, and am struggling to figure this out.
from subprocess import call
def callAlias():
call("myAlias")
callAlias()
我也计划添加更多,但我在第一步中遇到了障碍.:P
I plan on adding more too it, but I hit the snag on my first step. :P
我会发布更多信息,但我必须小心处理很多敏感的机密内容.抱歉,代码含糊不清,缺少错误输出.
I would post more, but there's a lot of sensitive confidential stuff I have to be careful with. Sorry for the vague code, and lack of error output.
解决方案
更新: 感谢您对这个 hack 解决问题的支持,我很高兴它有用.但是一个更好的答案是三人组的,在页面的下方徘徊......
Update: Thanks for the upvotes for this hack to workaround the problem, I'm glad it's useful. But a much better answer is tripleee's, languishing far down the page...
如果您需要的别名是在 ~/.bashrc 中定义的,那么由于以下几个原因它不会运行:
If the alias you require is defined in ~/.bashrc, then it won't get run for a few reasons:
1) 你必须给'shell'关键字arg:
1) You must give the 'shell' keyword arg:
subprocess.call('command', shell=True)
否则,您给定的命令将用于查找可执行文件,而不是传递给 shell,它是扩展别名和函数等内容的 shell.
Otherwise your given command is used to find an executable file, rather than passed to a shell, and it is the shell which expands things like aliases and functions.
2) 默认情况下,subprocess.call 和朋友使用'/bin/sh' shell.如果这是您要调用的 Bash 别名,则需要使用可执行"关键字 arg 告诉子进程使用 bash 而不是 sh:
2) By default, subprocess.call and friends use the '/bin/sh' shell. If this is a Bash alias you want to invoke, you'll need to tell subprocess to use bash instead of sh, using the 'executable' keyword arg:
subprocess.call('command', shell=True, executable='/bin/bash')
3) 但是,/bin/bash 不会获取 ~/.bashrc,除非作为交互式"shell(使用-i")启动.不幸的是,您不能传递 executable='/bin/bash -i',因为它认为整个值是可执行文件的名称.因此,如果您的别名是在用户的正常交互式启动中定义的,例如在 .bashrc 中,那么您必须使用这种替代形式调用命令:
3) However, /bin/bash will not source ~/.bashrc unless started as an 'interactive' shell (with '-i'.) Unfortunately, you can't pass executable='/bin/bash -i', as it thinks the whole value is the name of an executable. So if your alias is defined in the user's normal interactive startup, e.g. in .bashrc, then you'll have to invoke the command using this alternative form:
subprocess.call(['/bin/bash', '-i', '-c', command])
# i.e. shell=False (the default)
相关文章