[英]Run a .sh file with Python 3 Idle
I am trying run a sh file with python 3. My .sh file will work on Terminal. 我正在尝试使用python 3运行sh文件。我的.sh文件将在Terminal上运行。 My operating system is Raspbian.
我的操作系统是Raspbian。 I try that code :
我尝试该代码:
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)
but it not works... 但它不起作用...
The is undoubtedly a permissions issue. 无疑是一个权限问题。 In order to be able to "directly" execute a file (a la "dot slash" -
./yourfile
), the file in question needs the "execute bit" set. 为了能够“直接”执行文件(例如“。”,即
./yourfile
),相关文件需要设置“执行位”。 Try using ls -l
to see the file you've just created with your script. 尝试使用
ls -l
查看刚刚使用脚本创建的文件。 I'll bet the file does not have the execute bit: 我敢打赌,该文件不执行位:
$ ls -l ./step.sh
-rw-r--r-- 1 furkan furkan 0 Nov 13 20:51 step.sh
Note the lack of x
in that first column. 请注意,第一列中缺少
x
。 You might chmod
to add the execute bit: 您可以使用
chmod
添加执行位:
$ chmod +x ./step.sh
$ ls -l ./step.sh
-rwxr-xr-x 1 furkan furkan 0 Nov 13 20:51 step.sh
With the execute bit set, you could then use a "dot slash" construct. 设置好执行位后,您便可以使用“点斜线”构造。
However, I doubt you want to execute chmod
from within your script, so instead tell your script the actual program you want to run step.sh
, namely, sh
: 但是,我怀疑您是否想在脚本中执行
chmod
,所以要告诉脚本您要运行step.sh
的实际程序,即sh
:
shellscript=subprocess.Popen(['sh', './step1.sh'], stdin=subprocess.PIPE)
Or in the simple case of your example, simply go directly to sudo: 或者在您的示例的简单情况下,只需直接转到sudo即可:
shellscript=subprocess.Popen(['sudo', 'yourexecutable'], stdin=subprocess.PIPE)
Note that if you're being robust, I might consider adding some absolute paths, or ensuring your PATH variable is set. 请注意,如果您很健壮,我可能会考虑添加一些绝对路径,或确保已设置PATH变量。 However the key to your problem is the misunderstanding of what 'executable' means.
但是,解决您问题的关键是对“可执行文件”含义的误解。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.