Python脚本不会在键盘快捷键上运行

时间:2014-11-04 11:58:30

标签: python linux bash keyboard-shortcuts redhat

所以我有很多脚本可以通过键盘快捷键运行,例如将屏幕截图上传到imgur并将链接放在剪贴板中,用于数字化绘图的内容等等。

我有这个当前脚本,它只从终端运行,而不是当我尝试将其作为键盘快捷键运行时。

我试图通过System > Preferences > Keyboard Shortcuts上的Scientific linux 6.4运行它。

我已经包含了下面的脚本,以防有任何具体内容可以阻止它工作。

#!/usr/bin/python
import fileinput, os

import subprocess

from pygments import highlight
from pygments.lexers import get_lexer_by_name, guess_lexer
import pygments.formatters as formatters

#stdin = "\n".join([line for line in fileinput.input()])

p = subprocess.Popen(["xclip", "-selection", "primary", "-o"], stdout=subprocess.PIPE)
code, err = p.communicate()

if not err:

  lexer = guess_lexer(code)

  print lexer.name

  imageformatter = formatters.ImageFormatter(linenos=True, cssclass="source", font_name="Liberation Mono")
  formatter = formatters.HtmlFormatter(linenos=True, cssclass="source")

  HTMLresult = highlight(code, lexer, formatter)
  Jpgresult = highlight(code, lexer, imageformatter, outfile=open("syntax.png", "w"))

  with open("syntax.html", "w") as f:

    f.write("<html><head><style media='screen' type='text/css'>")
    f.write(formatters.HtmlFormatter().get_style_defs('.source'))
    f.write("</style></head><body>")
    f.write(HTMLresult)
    f.write("</body></html>")


#  os.system("pdflatex syntax.tex")

  os.system("firefox syntax.html")

  os.system("uploadImage.sh syntax.png")



else:
  print err

它的工作方式是使用xclip提取剪贴板选择,在文本上使用pygments,然后创建一个html文档并在firefox中打开它,并将图像上传到imgur (使用我拥有的另一个脚本,我知道100%有效),然后将该图像网址放回剪贴板。

它所在的bin文件夹位于我的路径中。

我已经尝试了所有:

script
script.sh (where this file is just a shell script which calls the python script)
/home/will/bin/script
/home/will/bin/script.sh

作为command中的keyboard preferences

如果我将这些脚本的内容更改为类似notify-send "hello"之类的内容,然后生成通知消息,那么我相当自信它会对脚本产生疑问,而不是{ {1}}菜单。

4 个答案:

答案 0 :(得分:2)

我遇到了完全相同的问题。以下是我修复它的方法:

首先,我编写了一个单线程shell脚本,看起来像python /home/user/Scripts/script.py,其中“/home/user/Scripts/script.py”是我的Python的位置。我将此shell脚本放在可执行路径中。

接下来,当我去创建快捷方式时,我没有告诉计算机运行该文件。我告诉计算机启动终端并将shell脚本作为该终端的参数。就我而言,它看起来像:xfce4-terminal -x ralia.sh

这适合我。

答案 1 :(得分:0)

可能的问题是$ PATH在您的交互式shell与守护程序或处理键盘快捷键的程序的环境之间存在差异。

在“import os”之后立即尝试:

open("/tmp/debug.txt", "w").write(os.environ["PATH"])

然后使用键盘快捷键运行它并查看/tmp/debug.txt

→尝试二进制文件的绝对路径,如果这没有帮助,请考虑jhutar的建议。

答案 2 :(得分:0)

问题出在“with open(”syntax.html“,”w“)为f:”。 使用脚本的键盘快捷键时,请使用脚本中文件的完整路径。

而不是:

with open("syntax.html", "w") as f:

使用:

with open("/home/user/my_script_folder/syntax.html", "w") as f:

将脚本中的所有文件名更改为完整路径,它应该可以正常工作。

答案 3 :(得分:0)

我有一个类似的问题。问题在于,必须使用完整路径才能使其通过键盘快捷键起作用。

就我而言,这不起作用:

#!/bin/bash
python scrypt.py

但是,这确实可行:

#!/bin/bash
python /home/user/bin/scrypt.py
相关问题