1

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)

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.