从 python 运行另一个程序
我想从 python 代码多次调用一个程序,并将该程序的输出保存在一个文本文件中。我现在的第一个问题是调用其他代码。我必须重定向到另一个目录并在output.txt 上调用./rank。这就是我尝试这样做的方式:
TheCommand = "~/src/rank-8-9-2011/rank output.txt"
os.system(TheCommand)
但是我遇到了解析错误。
[Parsing error on line ]Unknown error: 0
我在 Mac OS 10.5.8 上运行 python2.7。我不确定问题是什么。我也尝试使用子进程:
subprocess.call(["~/src/rank-8-9-2011/rank", "output.txt"])
这找不到目录(我有一种感觉,我错误地使用了子进程),但我不知道 os.system 有什么问题。
I want to call a program multiple times from a python code, and save the output of that program in a text file. My first problem right now is just calling the other code. I have to redirect to a different directory and call ./rank on output.txt. This is how Im trying to do it:
TheCommand = "~/src/rank-8-9-2011/rank output.txt"
os.system(TheCommand)
but im getting a parsing error.
[Parsing error on line ]Unknown error: 0
Im running python2.7 on Mac OS 10.5.8. Im not sure what the problem is. I also tried using subprocess:
subprocess.call(["~/src/rank-8-9-2011/rank", "output.txt"])
This does not find the directory (I have a feeling Im using the subprocess incorrectly), but I dont know what is wrong with the os.system.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
subprocess.Popen
第一个参数中的程序名称不得包含~
,因为它不会将字符串传递到 shell 进行处理(就像始终使用参数化sql 中的查询,保护用户免受字符串注入攻击,例如,如果不是output.text
而是;rm -rf /
,则系统版本将运行rank< /code> 然后运行 rm -rf .
但subprocess.Popen
只会让rank
打开一个名为;rm -rf .
) 的文件,因此应该展开通过调用 os.path.expanduser 来实现:虽然可以通过传递 shell=True 来打开 shell 处理,但由于上述原因,不建议这样做。
the name of the program in the first argument to
subprocess.Popen
must not contain~
as it doesn't pass the string to the shell for processing (which like always using parameterized queries in sql, protects one from string injection attacks, e.g. if instead ofoutput.text
one had;rm -rf /
, the system version would runrank
and then runrm -rf .
but thesubprocess.Popen
would only haverank
open a file named;rm -rf .
), so one should expand it by callingos.path.expanduser
:although it is possible to turn shell processing on by passing
shell=True
, it is not recommended for the aforementioned reason.你应该尝试 http://docs.python.org/library/ os.path.html#os.path.expanduser
you should try http://docs.python.org/library/os.path.html#os.path.expanduser
我相当确定您的解析错误来自
rank
,而不是来自您的 os.system 命令,因为那里看起来没有什么奇怪的。如果您手动运行rank
会发生什么?subprocess
似乎有“~”的问题,尽管我不能立即确定原因。输入完整路径,它应该可以工作(尽管如果确实是rank
的问题,您可能会遇到解析错误)。I'm fairly certain your parsing error is coming from
rank
, not from your os.system command, as nothing there looks weird. What happens if you runrank
manually?subprocess
seems to have a problem with '~', although I'm not immediately sure why. Put the full path and it should work (although you'll likely get that parsing error if it is indeed a problem withrank
).