运行 一个 .sh 文件 Python 3 空闲

Run a .sh file with Python 3 Idle

我正在尝试 运行 一个带有 python 的 sh 文件 3. 我的 .sh 文件将在终端上运行。我的操作系统是 Raspbian。我试试那个代码:

import time
import os
import subprocess

# STEP 1
text='sudo somecode'
savefile=open('step1.sh','w')
savefile.write(text)
savefile.close()
time.sleep(2)

shellscript=subprocess.Popen(['./step1.sh'], stdin=subprocess.PIPE)

但它不起作用...

这无疑是一个权限问题。为了能够 "directly" 执行文件(la "dot slash" - ./yourfile),相关文件需要 "execute bit" 集。尝试使用 ls -l 查看您刚刚使用脚本创建的文件。我敢打赌文件 没有 有执行位:

$ ls -l ./step.sh
-rw-r--r-- 1 furkan furkan 0 Nov 13 20:51 step.sh

请注意第一列中缺少 x。您可以 chmod 添加执行位:

$ chmod +x ./step.sh
$ ls -l ./step.sh
-rwxr-xr-x 1 furkan furkan 0 Nov 13 20:51 step.sh

设置执行位后,您可以使用 "dot slash" 结构。

但是,我怀疑你想从你的脚本中执行 chmod,所以告诉你的脚本你想要 actual 程序 运行 step.sh,即sh:

shellscript=subprocess.Popen(['sh', './step1.sh'], stdin=subprocess.PIPE)

或者在您示例的简单情况下,只需直接转到 sudo:

shellscript=subprocess.Popen(['sudo', 'yourexecutable'], stdin=subprocess.PIPE)

请注意,如果您很健壮,我可能会考虑添加一些绝对路径,或确保您的 PATH 变量已设置。然而,问题的关键是对 'executable' 含义的误解。