使用python运行另一个程序? [英] Using python to run another program?

查看:50
本文介绍了使用python运行另一个程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从命令行运行的程序,如下所示:

I have a program that I run from the command line that looks like this:

$ program a.txt b.txt

该程序需要两个文本文件作为参数.我正在尝试编写一个 Python 3.2 脚本来运行上述程序.我怎样才能做到这一点?目前,我正在尝试像这样使用 subprocess 模块:

The program requires two text files as arguments. I am trying to write a Python 3.2 script to run the above program. How can I do this? Currently, I am trying to use the subprocess module like this:

import subprocess

with open("a.txt", mode="r") as file_1:
    with open("b.txt", mode="r") as file_2:
        cmd = ['/Users/me/src/program', file_1, file_2]
        process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
        for line in process.stdout:
            print(line)

我阅读了这篇文章这里,这似乎描述了我的问题的类似解决方案.不幸的是,在阅读了这些帖子后,我似乎仍然无法让我的 Python 代码运行我的程序.

I read this post and the post here, which seem to describe similar solutions to my problem. Unfortunately, after reading these posts, I still can't seem to make my Python code run my program.

有人可以帮忙吗?提前致谢!

Can anyone help? Thanks in advance!

推荐答案

subprocess.Popen 需要一个字符串数组.该数组中的两个项目是文件句柄.您需要将实际文件名称传递给您尝试运行的程序.

subprocess.Popen expects an array of strings. Two of the items in that array are file handles. You need to pass the actual file name to the program you're trying to run.

cmd = ['/Users/me/src/program', 'a.txt', 'b.txt']

你可以完全去掉 with open(...) as ... 行.

You can get rid of the with open(...) as ... lines completely.

这篇关于使用python运行另一个程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆