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

查看:62
本文介绍了在所选文件上运行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运行一个脚本,该脚本接收文件路径和要上传文件的文件名。编写将文件上传到Web的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:\Your\File\uploadscript.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:\Your\File\uploadscript.py %1
  SHIFT
  GOTO upload_loop
:completed

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

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