Shell脚本:从shell脚本中执行python程序

Har*_*pal 114 python shell

我试过谷歌搜索答案,但没有运气.

我需要使用我的工作超级计算机服务器,但是为了运行我的python脚本,它必须通过shell脚本执行.

例如,我想job.sh执行python_script.py

如何实现这一目标?

Jea*_*sen 162

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

python path/to/the/python_script.py
Run Code Online (Sandbox Code Playgroud)

细节:

  • 在文件job.sh中,放这个
#!/bin/sh
python python_script.py
Run Code Online (Sandbox Code Playgroud)
  • 执行此命令以使脚本可以为您运行: chmod u+x job.sh
  • 运行 : ./job.sh

  • 这取决于您的系统。Python 3 可能是默认的 Python 运行时,也可能不是。你可以通过运行 `python --version` 来检查,你可以使用 `python3 hello.py` 强制执行版本。 (2认同)

小智 97

方法1 - 创建shell脚本:

假设你有一个python文件hello.py 创建一个名为job.shcontains 的文件

#!/bin/bash
python hello.py
Run Code Online (Sandbox Code Playgroud)

使用标记它可执行

$ chmod +x job.sh
Run Code Online (Sandbox Code Playgroud)

然后运行它

$ ./job.sh
Run Code Online (Sandbox Code Playgroud)

方法2(更好) - 让python本身从shell运行:

修改脚本hello.py并将其添加为第一行

#!/usr/bin/env python
Run Code Online (Sandbox Code Playgroud)

使用标记它可执行

$ chmod +x hello.py
Run Code Online (Sandbox Code Playgroud)

然后运行它

$ ./hello.py
Run Code Online (Sandbox Code Playgroud)

  • `#!/ usr/bin/env python`就是我要找的〜谢谢! (6认同)
  • 请编辑您的答案,使其更具可读性.您可以使用答案编辑器中的101010按钮将脚本内容标记为代码. (5认同)

Enr*_*sso 10

Imho,写作

python /path/to/script.py
Run Code Online (Sandbox Code Playgroud)

是非常错的,特别是在这些日子里.哪个蟒蛇?python2.6的?2.7?3.0?3.1?大多数时候你需要在python文件的shebang标签中指定python版本.我鼓励使用

#!/usr/bin/env python2 #or python2.6 or python3 or even python3.1
兼容性.

在这种情况下,让脚本可执行并直接调用它会好得多:

#!/bin/bash

/path/to/script.py

这样你需要的python版本只能写在一个文件中.现在大多数系统都在使用python2和python3,并且碰巧symlink python指向python3,而大多数人都希望它指向python2.


Nis*_*gle 9

将以下程序另存为print.py

#!/usr/bin/python3
print('Hello World')
Run Code Online (Sandbox Code Playgroud)

然后在终端类型中:

chmod +x print.py
./print.py
Run Code Online (Sandbox Code Playgroud)


Shp*_*gle 5

你应该能够调用它,python scriptname.py例如

# !/bin/bash

python /home/user/scriptname.py 
Run Code Online (Sandbox Code Playgroud)

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

您可以使用chmod u+x scriptname.py.


gee*_*rsh 5

这对我有用:

  1. 创建一个新的 shell 文件作业。所以让我们说: touch job.sh并添加命令来运行 python 脚本(您甚至可以向该 python 添加命令行参数,我通常预定义我的命令行参数)。

    chmod +x job.sh

  2. 在里面job.sh添加以下py文件,让我们说:

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

    python_file1.py argument1 argument2 argument3 >> testpy-output.txt && echo "Done with python_file1.py"

job.sh 的输出应如下所示:

Done with python_file.py

Done with python_file1.py

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

注意:只需快速了解这里发生的事情:

python_file.py argument1 argument2 argument3 >> testpy-output.txt && echo "completed with python_file.py" . 
Run Code Online (Sandbox Code Playgroud)
  • 这里 shell 脚本将运行文件python_file.py并在运行时向 python 文件添加多个命令行参数
  • 这并不一定意味着您还必须传递命令行参数。
  • 你可以像这样使用它:python python_file.py,简单明了。接下来,>>将打印此 .py 文件的输出并将其存储在 testpy-output.txt 文件中。
  • &&是一个逻辑运算符,只有在上述内容成功执行后才会运行,并且作为可选的回声“用 python_file.py 完成”将在运行时回显到您的 cli/终端。