Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
444 views
in Technique[技术] by (71.8m points)

windows - Run Python Script on Selected File

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".

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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

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.

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

EDIT: 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...