McM
McM

Reputation: 471

How to execute a terminal command within a specified directory using python?

I know I can use the os module to operate in the terminal from within a python script using something like:

import os

os.system("python execute_code.py")

But that restricts me from either writing code specifically from the directory in which my python lives, or writing code that operates on files using the full path to the files. Is there a way to move into directories and execute the command from those directories.

For example, the way I would do it now is:

exe_path = "/path/to/file"

os.system("python modifyFile.py " + exe_path + file)

How could I instead go:

# move to directory
os.system("python modifyFile.py " + file)

Upvotes: 1

Views: 833

Answers (1)

Barmar
Barmar

Reputation: 780818

Use the full pathname of the script.

os.system(f"python '{exe_path}/modifyFile.py'")

or use a cd command

os.system(f"cd '{exe_path}' && python modifyFile.py")

The && makes it skip the python command if cd fails.

Upvotes: 1

Related Questions