Home > Software design >  subprocess.call makes unwanted action
subprocess.call makes unwanted action

Time:09-21

I run this function to make moving files finish before other script lines are read. When I move video files subprocess.call moves and plays the video.

I what to avoid playing. How can I do that. There is an option to send output to NULL. stdout=subprocess.DEVNULL. But it did not help.

    def move_files_while_script_waits(src, dest):
        try:
            for a_file in os.listdir(src):
                old_place = os.path.join(src, a_file)
                new_place = os.path.join(dest, a_file)
                subprocess.call(shutil.move(old_place, new_place),shell=True)
        except Exception as e:
            print(e)

CodePudding user response:

Maybe you don't need shutil.move, perhaps ?

Try this :

def move_files_while_script_waits(src, dest):
    try:
        for a_file in os.listdir(src):
            old_place = os.path.join(src, a_file)
            new_place = os.path.join(dest, a_file)
            subprocess.call(["powershell", "-Command", fr"mv {old_place} {new_place}"])

    except Exception as e:
        print(e)

CodePudding user response:

subprocess.call(shutil.move(old_place, new_place),shell=True)

Is doing two things:

  1. shutil.move(old_place, new_place) moves the file to the new location
  2. subprocess.call(..., shell=True) on the return value of shutil.move (the path to the destination file) is likely recognizing specific file extensions for video files and launching them with the default handler application.

If you don't want to play the files, just get rid of subprocess.call, changing the line to:

shutil.move(old_place, new_place)

which will move the files on its own (it's not an external utility, so subprocess isn't needed to move the files at all), and not try to "invoke" them for the Windows definition of "running" video files.

CodePudding user response:

You can also try to have the call sent in a string, but not a usual method call:

    def move_files_while_script_waits(src, dest):
        try:
            for a_file in os.listdir(src):
                old_place = os.path.join(src, a_file)
                new_place = os.path.join(dest, a_file)
                subprocess.call(f"shutil.move({old_place}, {new_place})",shell=True)
        except Exception as e:
            print(e)

However, linux command mv version will work fine as well, unless there is no any specific reason of shutil.move

    def move_files_while_script_waits(src, dest):
        try:
            for a_file in os.listdir(src):
                old_place = os.path.join(src, a_file)
                new_place = os.path.join(dest, a_file)
                subprocess.call("mv", old_place, new_place,shell=True)
        except Exception as e:
            print(e)
  • Related