简体   繁体   中英

Running Shell script from within Python issue

So, I am trying to run a Shell script from Python and I double checked that the location of the script.sh is all correct (because when I run it from sublime, the script.sh opens). What I have to call script.sh is:

subprocess.call("script.sh", shell=True)

When I run that, the function returns 0. However, the script is supposed to create a file in my folder and write into it, which it is not doing. It does work when I run the script from cygwin command prompt.

What could be wrong?

Please ensure you have added:

!/bin/bash

as the first line and also make sure that the file script.sh has executable permission.

chmod u+x script.sh

then try specifying the complete path:

subprocess.call("/complete/path/script.sh", shell=True)

At the top of your shell script somewhere, put the line:

pwd >/tmp/mytempfile

and then run the Python script and go look into that file.

This will let you find out the working directory of your scripts which, in the majority of cases where a file doesn't appear to be created, is different to what you think it should be.

You may also want to check the shell script to ensure it's not changing the working directory before creating the file but that would be unlikely given you've stated it works okay from the command line.

If you add the line to create the temporary file and it doesn't actually get created, then your script is not executing.

In that case, you could try a few things. The first is to fully specify the script on the off chance that Python isn't in the correct directory. In other words, something like:

subprocess.call("/actual/path/to/script.sh", shell=True)

Or you could try to run the actual bash executable with the script as an argument:

subprocess.call("bash -c script.sh", shell=True)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM