1

我想用几句话来完成的是:更改目录并从 shell 调用脚本。

到目前为止,我已经设法用os.chdir().

但是我无法理解如何编写给定任务的第二部分。具体来说,我要调用的命令就是这个命令, /path-to-dir-of-the-script/script<inputfile.txt>outfile.txt在我看来,至少问题是输入文件(显然是不存在但将由脚本生成的输出文件)位于两个不同的目录中。

因此,通过尝试以下(或多或少用于调试和监督目的)以及各种修改,我总是会遇到错误lsprintSyntaxError 或系统找不到这两个文件等。

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

我确信我的方法中有不止一个错误(除了我的语法),我可能需要研究更多。到目前为止,我已经查看了文档,其中包括一些Popen示例和两三个相关的问题,这里这里这里

如果我没有让自己清楚一些注释:

脚本和文件不在同一级别。该命令是有效的,并且在涉及到它时可以完美地工作。移动文件,脚本到同一级别都不起作用。

有什么建议么??

4

1 回答 1

2

使用引号在 Python 中创建字符串,例如:

com = "/path-to-dir-of-the-script/script"

您可以使用cwd参数来运行具有不同工作目录的脚本,例如:

subprocess.check_call(["ls"]) # read the contents of the current dir
subprocess.check_call(["ls"], cwd="/path-to-dir") 

要模拟 bash 命令:

$ /path-to-dir-of-the-script/script < inputfile.txt > outfile.txt

使用subprocess模块:

import subprocess

with open("inputfile.txt", "rb") as infile, open("outfile.txt", "wb") as outfile:
     subprocess.check_call(["/path-to-dir-of-the-script/script"],
                           stdin=infile, stdout=outfile)
于 2013-07-17T14:55:30.553 回答