-2

I want to add "source_paths" to my script so that it can run on an external directory using cmd.bat

Example cmd.bat

echo off
    Rename.py [Folder_Images] [listname.txt]
pause

code script Rename.py

import pathlib

IMG_DIR = pathlib.Path('.\Folder_Images')

with open('listname.txt') as jabber:
    content = jabber.read().splitlines()
    director = sorted(IMG_DIR.iterdir())
    for src, dest in zip(director, content):
        src.rename(IMG_DIR / f'{dest}{src.suffix}')

I found this code I tried to add I get an error no such file.

Code

if __name__ == '__main__':
    import os
    import sys
    source_paths = []
    if len(sys.argv) > 1:
        for i, path in enumerate(sys.argv[1:]):
            if i < 2 and not os.path.isfile(path):
                raise ValueError(f'Not a valid path or file does not exist: {path}')
            source_paths.append(path)        
        if i < 2:
            raise ValueError(f'Three path arguments needed')
        source_paths = source_paths[0:2]
        source_paths = [os.path.abspath(path)  for path in source_paths]
        Rename(source_paths[0], source_paths[1])
pppery
  • 3,731
  • 22
  • 33
  • 46
  • Which script do you have an issue with? The Rename.py or the other code? Where did you try to add source_paths? What error was displayed? Have you tried anything to debug? Please see [ask] and [mcve]. – Nic3500 May 23 '23 at 20:11

1 Answers1

0

If I understand you correctly, you are looking for a way to pass a variable (e.g. source_path) to your python script, from the command line. So, in your windows script that you use to call your python script, you define the var source_path = ..., and then in python you can use it, correct?

Do this in two steps:

  1. Define a variable in your windows/Powershell/cmd script (cmd.bat), that you can pass to your python script, like explained here
  2. Make your python script understand that it is being called with an argument. I would advise against importing the sys and os modules for that (looks like that's what you tried in your code example), and instead use the argparse module, like explained here

Not sure why you would need 2 scripts, then, in the first place. If the var is truly variable (i.e., changing often), then you might just want to call you python script directly from the command line,s specifying the var everytime that you call the script. And if it's kind of static, and you're always using one of the same 3-5 choices, why not add a dictionarty to the python script and keeping the data in there? 2 scripts calling each other, only passing one var, seems like a bit of an unnecessary complication?!

KingOtto
  • 840
  • 5
  • 18