我正在尝试在我的python脚本中运行一个bash脚本,我确信有一种方法可以做我的bash脚本在python中所做的事情,但我更专注于让它工作。
以下是我以root身份运行的代码,后跟错误:
import subprocess
#variable = subprocess.check_output('dmidecode', shell=True)
#print(variable)
#run program once as root then cron it as root
try :
file = open("/var/log/serialcontrol/dmidecode.txt", "r")
except FileNotFoundError:
file = open('/var/tmp/serialcontrol.bash', 'w')
file.write("#!/bin/bash/\nif [ ! -d /var/log/serialcontrol/]\nthen\n\tmkdir /var/log/serialcontrol/\nfi");
file.close()
subprocess.call("/var/tmp/serialcontrol.bash")
继承错误
Traceback (most recent call last):
File "/home/trisimix/serialcontrol/serialcontrol.py", line 6, in <module>
file = open("/var/log/serialcontrol/dmidecode.txt", "r")
FileNotFoundError: [Errno 2] No such file or directory: '/var/log/serialcontrol/dmidecode.txt'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/trisimix/serialcontrol/serialcontrol.py", line 11, in <module>
subprocess.call("/var/tmp/serialcontrol.bash")
File "/usr/lib/python3.5/subprocess.py", line 557, in call
with Popen(*popenargs, **kwargs) as p:
File "/usr/lib/python3.5/subprocess.py", line 947, in __init__
restore_signals, start_new_session)
File "/usr/lib/python3.5/subprocess.py", line 1551, in _execute_child
raise child_exception_type(errno_num, err_msg)
PermissionError: [Errno 13] Permission denied
答案 0 :(得分:2)
您在处理/var/tmp/serialcontrol.bash
时创建的FileNotFoundError
文件不可执行。在尝试使用subprocess
执行它之前,先使其可执行。
import subprocess
import os
import stat
#variable = subprocess.check_output('dmidecode', shell=True)
#print(variable)
#run program once as root then cron it as root
try :
file = open("/var/log/serialcontrol/dmidecode.txt", "r")
except FileNotFoundError:
script = '/var/tmp/serialcontrol.bash'
with open(script, 'w') as file:
file.write("#!/usr/bin/env bash/\nif [ ! -d /var/log/serialcontrol/]\nthen\n\tmkdir /var/log/serialcontrol/\nfi");
st = os.stat(script)
os.chmod(script, st.st_mode | stat.S_IEXEC)
subprocess.call(script)
正如@anishsane在评论中指出的那样,chmod
- 脚本的另一种替代方法就是这样调用它,然后放弃chmod
:
subprocess.call(["/bin/bash", script])
实际上,如果我们可以假设bash
在PATH
上,那么这将更加便携:
subprocess.call(["bash", script])