我试着在谷歌上搜索答案,但一无所获。
我需要使用我的作品超级计算机服务器,但我的python脚本运行,它必须通过一个shell脚本执行。
例如,我希望job.sh执行python_script.py
如何才能做到这一点呢?
我试着在谷歌上搜索答案,但一无所获。
我需要使用我的作品超级计算机服务器,但我的python脚本运行,它必须通过一个shell脚本执行。
例如,我希望job.sh执行python_script.py
如何才能做到这一点呢?
当前回答
你应该能够调用它作为python scriptname.py。
# !/bin/bash
python /home/user/scriptname.py
还要确保脚本具有运行权限。
您可以使用chmod u+x scriptname.py使其可执行。
其他回答
这里我演示了一个在shell脚本中运行python脚本的示例。出于不同的目的,您可能需要从shell命令中读取输出,在同一个文件中执行python脚本和shell命令。
使用os.system()方法从python中执行shell命令。要从shell命令读取输出,请使用os.popen()。
下面是一个示例,它将grep所有包含文本sample_program.py的进程。然后在收集了进程id(使用python)之后,它会将它们全部杀死。
#!/usr/bin/python3
import os
# listing all matched processes and taking the output into a variable s
s = os.popen("ps aux | grep 'sample_program.py'").read()
s = '\n'.join([l for l in s.split('\n') if "grep" not in l]) # avoiding killing the grep itself
print("To be killed:")
print(s)
# now manipulating this string s and finding the process IDs and killing them
os.system("kill -9 " + ' '.join([x.split()[1] for x in s.split('\n') if x]))
引用:
在shell脚本中执行python程序 指定os的输出。系统的一个变量,并防止它显示在屏幕上
将以下程序保存为print.py:
#!/usr/bin/python3
print('Hello World')
然后在终端类型中:
chmod +x print.py
./print.py
你应该能够调用它作为python scriptname.py。
# !/bin/bash
python /home/user/scriptname.py
还要确保脚本具有运行权限。
您可以使用chmod u+x scriptname.py使其可执行。
这个方法最适合我: 在脚本顶部添加以下内容:
#!c:/Python27/python.exe
(C:\Python27\python.exe是我机器上python.exe的路径) 然后运行脚本通过:
chmod +x script-name.py && script-name.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来提供参数