user1050619
user1050619

Reputation: 20856

Unable to find file or directory Python subprocess

I'm trying to call a Python module but get the following error "test.sh not found"

but this file is found in the directory.

process = subprocess.Popen("test.sh",shell=True)

The script and the sh file are located in the same directory.

Upvotes: 1

Views: 2651

Answers (1)

jfs
jfs

Reputation: 414215

By default the current directory is not in PATH therefore just "test.sh" is not found, the minimal change is to use "./tests.sh".

To run a shell script, make sure you have a valid shebang e.g., #!/bin/sh and the file has executable permissions (chmod u+x test.sh).

If you are running Python script from a different directory then you also need to provide the full path:

#!/usr/bin/env python
import os
import sys
from subprocess import check_call

script_dir = os.path.realpath(os.path.dirname(sys.argv[0]))
check_call(os.path.join(script_dir, "test.sh"))

Note: there is no shell=True that starts the additional unnecessary shell process here. realpath resolve symlinks, you could use abspath instead if you want the path relative script's symlink instead of the script file itself.

Upvotes: 3

Related Questions