简体   繁体   English

从Python问题中运行Shell脚本

[英]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). 因此,我尝试从Python运行Shell脚本,并再次检查script.sh的位置是否正确(因为当我从sublime运行该脚本时, script.sh将打开)。 What I have to call script.sh is: 我必须叫script.sh是:

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. 当我运行该脚本时,该函数返回0。但是,该脚本应该在我的文件夹中创建一个文件并将其写入,但实际上并没有这样做。 It does work when I run the script from cygwin command prompt. 当我从cygwin命令提示符运行脚本时,它确实起作用。

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. 作为第一行,并确保文件script.sh具有可执行权限。

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: 在您的Shell脚本顶部的某处,放置以下行:

pwd >/tmp/mytempfile

and then run the Python script and go look into that file. 然后运行Python脚本并进入该文件。

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. 您可能还需要检查shell脚本,以确保在创建文件之前它不会更改工作目录,但是如果您从命令行说它可以正常工作,那将不太可能。

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. 一种是完全指定脚本,以免Python不在正确的目录中。 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: 或者,您可以尝试使用脚本作为参数运行实际的bash可执行文件:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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