【发布时间】:2013-07-17 14:44:49
【问题描述】:
我想用几句话来完成:更改目录并从 shell 调用脚本。
到目前为止,我已经设法使用 os.chdir() 更改目录。
但是我无法理解如何编写给定任务的第二部分。
具体来说,我要调用的命令就是这个
/path-to-dir-of-the-script/script<inputfile.txt>outfile.txt 至少在我看来问题是输入文件(显然是不存在但将由脚本生成的输出文件)位于两个不同的目录中。
因此,通过尝试以下操作(ls 和 print 或多或少用于调试和监督目的)以及各种修改,我总是会遇到错误。要么是 SyntaxError 要么系统找不到这两个文件等等。
import subprocess
import os
import sys
subprocess.call(["ls"]) #read the contents of the current dir
print
os.dir('/path-to-dir')
subprocess.call(["ls"])
print
in_file = open(infile.txt) #i am not sure if declaring my files is a necessity.
out_file = open (outfile.txt)
com = /path-to-dir-of-the-script/script
process = subprocess.call([com], stdin=infile.txt, stdout=outfile.txt)
这是它的最后一个实现,它生成:NameError: nameinfileis not defined
我确信我的方法中存在不止一个错误(除了我的语法),我可能需要研究更多。到目前为止,我已经查看了doc,其中包括一些Popen 示例和两三个相关问题here、here 和here。
如果我没有让自己清楚一些注释:
脚本和文件不在同一级别。该命令是有效的,并且在涉及到它时可以完美地工作。移动文件,脚本到同一级别都不起作用。
有什么建议吗??
【问题讨论】:
标签: python-2.7 subprocess