【问题标题】:Python sub process callPython子进程调用
【发布时间】:2013-07-17 14:44:49
【问题描述】:

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

到目前为止,我已经设法使用 os.chdir() 更改目录。

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

因此,通过尝试以下操作(lsprint 或多或少用于调试和监督目的)以及各种修改,我总是会遇到错误。要么是 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 示例和两三个相关问题hereherehere

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

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

有什么建议吗??

【问题讨论】:

    标签: python-2.7 subprocess


    【解决方案1】:

    在 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)
    

    【讨论】:

    • 我更喜欢您使用subprocess 模块提出的第二种方法。这对我来说更简单,而且显然效果很好!谢谢
    猜你喜欢
    • 1970-01-01
    • 2017-10-08
    • 1970-01-01
    • 2015-07-18
    • 2013-06-25
    • 2016-03-02
    • 2013-08-18
    • 2015-12-10
    • 1970-01-01
    相关资源
    最近更新 更多