“用 python 自动执行无聊的事情”第 6 章中的“mclip.py”批处理文件未按预期工作

问题描述 投票:0回答:1

我正在为项目:多剪贴板自动消息(在 Mu 中)编写代码。代码是在书中编写的,它可以从 cmd 到“python mclip.py 'keyphrase'”运行。但是,我无法从批处理文件运行代码,因为我陷入了 len(sys.argv) < 2 then sys.exit() (code attached)

我可以从批处理文件运行它的唯一方法是使用 sys.argv.append(input()) 我需要知道我是否可以这样做(我听说这是一个不好的做法)或者是否有更好的方法解决方案。

批处理文件信息: @py.exe C:\Users\kamal\pythonScripts\mclip.py %* @暂停

#! python3
# mclip.py - A multi-clipboard program.

TEXT = {'Agree': """Yes, I agree. That sounds fine to me.""",
'Busy': """Sorry, can we do this later this week or next week?""",
'upsell': """Would you consider making this a monthly donation?"""}

import sys, pyperclip
if len(sys.argv) < 2:
    print('Usage: python mclip.py [keyphrase] - copy phrase text')
    sys.exit()
    
keyphrase = sys.argv[1]     #first cmmand line arg is the keyphrase

if keyphrase in TEXT:
    pyperclip.copy(TEXT[keyphrase])
    print('Text for ' + keyphrase + ' copied to clipboard')
else:
    print('There is no text for ' + keyphrase)
python-3.x
1个回答
0
投票

我也遇到了同样的问题。这就是我修复它的方法(运行 Ubuntu 22.04.4 / Python 3.10.12):

Python脚本mclip.py(记录)

#! python
# mclip.py - A multi-clipboard program.

TEXT = {'agree': """Yes, I agree. That sounds fine to me.""",
    'busy': """Sorry, can we do this later this week or next week?""",
    'upsell': """Would you consider making this a monthly donation?"""}

import sys, pyperclip
if len(sys.argv) < 2:
print('Usage: python mclip.py [keyphrase] - copy phrase text')
sys.exit()

keyphrase = sys.argv[1]    # first command line arg is the keyphrase

if keyphrase in TEXT:
    pyperclip.copy(TEXT[keyphrase])
    print('Text for ' + keyphrase + ' copied to clipboard.')
else:
    print('There is no text for ' + keyphrase)

现在是您感兴趣的部分:bash 脚本 - mclip.sh

#!/usr/bin/env bash
echo "Enter an argument for Python-script mcclip (agree | busy | upsell):"
read INPUT
python PATH_TO_YOUR_PYTHON_SCRIPT/mclip.py $INPUT
bash

使 bash 脚本可执行

chmod u+x PATH_TO_YOUR_PYTHON_SCRIPT/mclip.sh

运行 bash 脚本

user@PC:~$ /PATH_TO_YOUR_PYTHON_SCRIPT/mclip.sh
Enter an argument for Python-script mcclip (agree | busy | upsell):
busy
Text for busy copied to clipboard.
© www.soinside.com 2019 - 2024. All rights reserved.