我试着在谷歌上搜索答案,但一无所获。

我需要使用我的作品超级计算机服务器,但我的python脚本运行,它必须通过一个shell脚本执行。

例如,我希望job.sh执行python_script.py

如何才能做到这一点呢?


当前回答

你应该能够调用它作为python scriptname.py。

# !/bin/bash

python /home/user/scriptname.py 

还要确保脚本具有运行权限。

您可以使用chmod u+x scriptname.py使其可执行。

其他回答

这对我来说很管用:

创建一个新的shell文件作业。所以我们说: touch job.sh和添加命令来运行python脚本(你甚至可以向python添加命令行参数,我通常预定义我的命令行参数)。 Chmod +x job.sh 在job.sh中添加以下py文件,假设: python_file.py参数1参数2参数3 >> test -output.txt && echo "Done with python_file.py" testpy-output.txt && echo "Done with python_file1.py"

Output of job.sh should look like this:

使用python_file.py完成

使用python_file1.py完成

我通常在必须运行多个具有不同预定义参数的python文件时使用这种方法。

注意:只是快速提醒一下这里发生了什么:

python_file.py argument1 argument2 argument3 >> testpy-output.txt && echo "completed with python_file.py" . 

Here shell script will run the file python_file.py and add multiple command-line arguments at run time to the python file. This does not necessarily means, you have to pass command line arguments as well. You can just use it like: python python_file.py, plain and simple. Next up, the >> will print and store the output of this .py file in the testpy-output.txt file. && is a logical operator that will run only after the above is executed successfully and as an optional echo "completed with python_file.py" will be echoed on to your cli/terminal at run time.

只需确保python可执行文件在PATH环境变量中,然后添加到脚本中

python path/to/the/python_script.py

细节:

在job.sh文件中,放入以下内容

# !/ bin / sh python python_script . py

执行chmod u+x job.sh命令,使脚本可运行 运行:./job.sh

将以下程序保存为print.py:

#!/usr/bin/python3
print('Hello World')

然后在终端类型中:

chmod +x print.py
./print.py

因为其他帖子说明了一切(我在寻找以下帖子时偶然发现了这篇帖子)。 下面是一种如何从另一个python脚本执行python脚本的方法:

Python 2:

execfile("somefile.py", global_vars, local_vars)

Python 3:

with open("somefile.py") as f:
    code = compile(f.read(), "somefile.py", 'exec')
    exec(code, global_vars, local_vars)

你可以通过提供其他的sys。argv来提供参数

我用这个,它工作得很好

#/bin/bash
/usr/bin/python python python_script.py