Home > Back-end >  Is it possible to pass arbitrary arguments to a function in a non-input way?
Is it possible to pass arbitrary arguments to a function in a non-input way?

Time:08-04

Is there a shortcut method such as dragging a file to pass the filename of the dragged file as a parameter to the open() function. For example, there are two files 00.py and 11.py. I drag 11.py onto 00.py and let go (open 11.py with 00.py), while "11.py" (file name) is passed as an argument to the open() function in 00.py.

CodePudding user response:

Hi @enter image description here

So I can't drag-and-drop drag_me.txt directly onto opener.py, but drag-and-drop works with drop_here.bat (because Windows recognizes the batch job as "executable" file)

Output

In the console output below, I redacted the absolute path of drag_me.txt for privacy reasons

Reading file 'C:\<redacted_for_privacy>\drag_me.txt'

Hello!

Press Enter to exit...

drag_me.txt

This is the file you want to open with your Python script. In this example, it just contains the string Hello!

drop_here.bat

This batch job "accepts" the dropped file and calls your Python script.

python opener.py %*
  • python opener.py executes the Python script using the system interpreter. If you're using a virtual environment, replace python with the path to the interpreter you're using (e.g. C:\venv\my_project\Scripts\python)
  • %* passes all arguments into the Python script. In this case, "all arguments" corresponds to drag_me.txt

opener.py

This is the Python script that opens drag_me.txt and prints its contents. The filename is taken from enter image description here

I should note, however, that using PyInstaller comes with its own caveats (e.g. having to make sure everything is packed correctly).

  • Related