簡體   English   中英

Python腳本不會在鍵盤快捷鍵上運行

[英]Python script won't run on keyboard shortcut

所以我有很多腳本,我從鍵盤快捷鍵運行,比如上傳截圖到imgur並將鏈接放在剪貼板中,用於數字化圖形的東西等等。

我有這個當前腳本,它只從終端運行,而不是當我嘗試將其作為鍵盤快捷鍵運行時。

我正試圖通過Scientific linux 6.4上的System > Preferences > Keyboard Shortcuts來運行它。

我已經包含了下面的腳本,以防有任何具體的內容可以阻止它工作。

#!/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

作為keyboard preferencescommand

如果我將這些腳本的內容更改為notify-send "hello" ,然后生成通知消息,那么我相當自信,這是腳本的問題,而不是keyboard shortcuts菜單。

我遇到了完全相同的問題。 以下是我修復它的方法:

首先,我編寫了一個單行shell腳本,看起來像python /home/user/Scripts/script.py ,其中“/home/user/Scripts/script.py”是我Python的位置。 我將此shell腳本放在可執行文件路徑中。

接下來,當我去創建快捷方式時,我沒有告訴計算機運行該文件。 我告訴計算機啟動終端並將shell腳本作為該終端的參數。 就我而言,它看起來像: xfce4-terminal -x ralia.sh

這適合我。

可能的問題是$ PATH在您的交互式shell與守護程序或處理鍵盤快捷鍵的程序的環境之間存在差異。

在“import os”之后立即嘗試:

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

然后使用鍵盤快捷鍵運行它並查看/tmp/debug.txt

→嘗試二進制文件的絕對路徑,如果這沒有幫助,請考慮jhutar的建議。

問題在於“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:

將腳本中的所有文件名更改為完整路徑,它應該可以正常工作。

我有類似的問題。 問題是必須使用完整路徑才能使用鍵盤快捷鍵。

就我而言,這不起作用:

#!/bin/bash
python scrypt.py

但是,這確實有效:

#!/bin/bash
python /home/user/bin/scrypt.py

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM