我有一个 Python 类,它应该通过将自身提交到集群环境来在后台执行一些任务。例如
class AwesomeTaskController(object):
def run(bunch_of_tasks):
for task in bunch_of_tasks:
cmd = "%s %s" % (os.path.abspath(__file__), build_cli_paramters(task))
# call the API to submit the cmd
if __name__ == "__main__":
#blah blah do stuff with given parameters
第一次举办此类类(class)时一切顺利。第一次运行时,会创建一个 pyc 文件。此 pyc 文件不可执行(权限方面)。
因此,我第二次使用此类时,该命令将直接使用 pyc 并提示权限被拒绝。也许我从错误的角度来看待这个问题?
最佳答案
.pyc 文件本身不可执行;您始终必须执行 .py 文件。 .pyc 文件只是 Python 即时生成的 .py 文件的编译版本,以便在下次运行 .py 文件时节省时间。
就您而言,您需要做的就是检查 __file__
是否以“.pyc”结尾并删除结尾的“c”。例如,您可以通过将脚本中的 __file__
替换为:
(__file__[:-1] if __file__.endswith(".pyc") else __file__)
这应该可以解决您的问题。
关于Python 脚本和类位于同一文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10344895/