Python不执行脚本

时间:2019-01-17 01:41:14

标签: python

我已经编写了Python代码来生成Shell脚本,然后使用子进程运行该脚本。

脚本文件已创建,但是当我尝试从代码中运行时,它没有执行任何操作。如果我尝试使用在脚本外部创建的文件运行相同的脚本,则该脚本将按预期运行。

这是我的代码:

import subprocess
import os

cwd = os.getcwd()
file_name = cwd + "/cmd_file_from_python"
fd = open(file_name,"w")
fd.write("#!/usr/local/bin/tcsh -f\n")
fd.write("echo 'PRINT FROM CMD_FILE_FROM_PYTHON'\n")
fd.close

os.chmod(file_name, 0o777)

cmd=file_name
p = subprocess.Popen(cmd,executable='/bin/ksh', shell=True, stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
(stdout,stderr) = p.communicate()
p_status = p.wait()
print "Command output : ", stdout
print "Command outerr : ", stderr
print "Command exit status/return code : ", p_status
print "================================================================"

file_name = cwd + "/cmd_file"
cmd = file_name
p = subprocess.Popen(cmd,executable='/bin/ksh', shell=True, stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
(stdout,stderr) = p.communicate()
p_status = p.wait()
print "Command output : ", stdout
print "Command outerr : ", stderr
print "Command exit status/return code : ", p_status

和输出:

Command output :
Command outerr :
Command exit status/return code :  0
================================================================
Command output :  PRINT FROM CMD_FILE

Command outerr :
Command exit status/return code :  0

这是我在代码外部创建的脚本代码:

$ cat cmd_file
#!/usr/local/bin/tcsh -f
echo 'PRINT FROM CMD_FILE'

如果我同时检查两个文件,则唯一的区别是打印:

$ diff cmd_file_from_python cmd_file
2c2
< echo 'PRINT FROM CMD_FILE_FROM_PYTHON'
---
> echo 'PRINT FROM CMD_FILE'

1 个答案:

答案 0 :(得分:1)

程序运行时,您的文件为空:

fd = open(file_name,"w")
fd.write("#!/usr/local/bin/tcsh -f\n")
fd.write("echo 'PRINT FROM CMD_FILE_FROM_PYTHON'\n")
fd.close

请注意,fd.close上没有通话限制;您实际上从未关闭过文件,因此文件的整个内容很可能都位于Python的缓冲区中,并且永远不会进入磁盘,直到程序结束为止(当CPython参考解释器作为实现的细节遍历并清理全局变量时,关闭具有副作用的打开文件;它可能永远不会到达另一个解释器的磁盘。

要解决此问题,请实际致电close。甚至更好的是,切换到更安全的with statement方法,其中close是隐式且自动的,即使发生异常或return导致您及早退出代码也是如此:

with open(file_name, "w") as fd:
    fd.write("#!/usr/local/bin/tcsh -f\n")
    fd.write("echo 'PRINT FROM CMD_FILE_FROM_PYTHON'\n")
# No need to call close; file is guaranteed closed when you exit with block