简体   繁体   中英

How can I make my Python script a system command and run it easily in any directory in Windows?

I am a Python rookie and I learn Python3.3 in Windows.

I wrote my first script, a script to rename files with incremental filenames. But by now, I had to copy my rename.py script to the directory I want to change the files names and run Python rename.py . It is not a very fancy way to use.

I can improve my code and pass the target directory to run my script in origin directory like Python rename.py .../TargetDir , but I have to copy the directory everytime.

So I want to make my script a system command, then I would only type rename in cmd.exe in the directory I want to rename a bunch of files. How can I approach this.

Use sys.argv to get the command line arguments. For example test.py :

import os
import sys

path = sys.argv[1]
print(os.listdir(path))

and then you can create a batch file which should placed in a folder that belongs to the PATH variable. In order to do so, create a text document with the following contents and save it as ListDir.bat . Copy the ListDir.bat to either your python folder, or Windows folder (both should be in your PATH )

ListDir.bat:

python C:\test.py "%CD%"
PAUSE

The %CD% refers to the current directory in the windows prompt. So assuming the python script test.py is in C:\\ the first line executes the test.py script with the argument current directory.

I used PAUSE to get user input before completing the script, you could choose not to.

After you save the ListDir.bat file. You can navigate to the folder you want to use it in, and just call ListDir

For this purpose, you'll want to use doskey , which allows you to set aliases for commands.

You use it like this:

doskey macroName=macroDefinition

So you would want to write something like this:

doskey rename=Python rename.py .

Where the . stands for the directory you're currently in. (I wasn't exactly clear on what you wanted -- the way I read your question was that you just want to cd into the directory where you want to rename a bunch of files, then run the script.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM