在选定文件上运行 Python 脚本 [英] Run Python Script on Selected File

查看:33
本文介绍了在选定文件上运行 Python 脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个 python 脚本来上传我在 Windows 资源管理器中选择的任何文件.这个想法是在 Windows 资源管理器中选择任何文件,右键单击以显示文件的上下文菜单,然后从那里选择一个命令......比如上传到 Web 服务器".

I would like to write a python script that would upload any file I select in Windows Explorer. The idea is to select any file in Windows Explorer, right-click to display file's Context Menu and select a command from there... something like "Upload to Web Server".

选择该命令后,Python 运行一个脚本,该脚本接收要上传的文件的文件路径和文件名.编写将文件上传到网络的 Python 脚本似乎很简单.不清楚的是如何在 Windows 上下文菜单中为 Python 脚本创建实体.以及如何将文件路径和文件名传递给Python脚本来捕捉....请指教!

After the command is selected, the Python runs a script which receives the file-path and a file name of the file to be uploaded. The writing the Python script that will upload the file to web seems to be straightforward. What is unclear is how to create an entity in Windows Context Menu for the Python Script. And how to pass the file path and file name to the Python script to catch.... Please advise!

推荐答案

假设是 Windows 7,如果您打开一个文件夹并在地址栏中键入shell:sendto",然后按 Enter 键,您将被带到上下文菜单.您可以添加一个包含以下内容的 .cmd 文件.

Assuming Windows 7, If you open a folder and type "shell:sendto" in the address bar then hit enter you'll be taken to the context menu. You can add a .cmd file with the following in it.

@echo off
cls
python C:YourFileuploadscript.py %1

这应该执行您的 python 脚本,传入文件 (%1) 作为参数.在 python 脚本中,您可以使用:

This should execute your python script passing in the file (%1) as a parameter. Within the python script you can use:

import sys
sys.argv  #sys.argv[1] is the file to upload

这会获取传入的所有参数,因此 sys.argv[1] 应该会为您提供传入的文件.我对此进行了测试,并且可以正常工作.您需要 .cmd 文件而不是直接转到 .py 的原因是因为 .py 文件不会显示在发送到"菜单中.

This gets all parameters passed in so sys.argv[1] should get you the file that was passed in. I tested this and it works. The reason you need the .cmd file instead of going right to the .py is because the .py file wont show up in the Send To menu.

关于获取传入文件的更多信息在这里:
在 Python 中接受文件参数(来自发送到上下文菜单)

More information on getting the file passed in is here:
Accepting File Argument in Python (from Send To context menu)

添加用于调用多个文件的脚本.请注意,这会在每个单独的文件上调用 python 脚本,如果您想将所有文件作为参数发送给 python 脚本,那么您需要做更多的工作.如果你想做更高级的事情,你需要研究批处理脚本.

Adding script for calling on multiple files. Note this calls the python script on each individual file, if you want to send all the files as a parameter to the python script then you'll need to do a bit more work. You need to research batch scripting if you want to do more advanced things.

@echo off
cls
:upload_loop
IF "%1"=="" GOTO completed
  python C:YourFileuploadscript.py %1
  SHIFT
  GOTO upload_loop
:completed

这篇关于在选定文件上运行 Python 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆