命令行需要文件作为参数,如何从Python程序中传递变量并写入?
说,我有命令行实用程序,其中输出文件是强制性参数:
process_data <output file>
我想要的是能够从Python代码运行此CMD命令, 但是,不用存储结果将其存储在Python变量中(Kinda重定向):
variable = None # currently empty
os.system(f"process_data {variable}")
在实用程序运行时,我希望将内容输入该变量,而应该写入“输出文件”:
print("output: ", variable)
output: "Data is processed successfully, here is the content of processing: ..."
Say, I have command line utility, where output file is mandatory argument:
process_data <output file>
What I want is to be able to run this CMD command from Python code,
but instead of storing result to file store it into Python variable (kinda redirect it):
variable = None # currently empty
os.system(f"process_data {variable}")
By the end of the utility runtime I wish to get content into that variable, that was supposed to be written to the "output file":
print("output: ", variable)
output: "Data is processed successfully, here is the content of processing: ..."
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
调用外部程序的清洁方法是使用Python
子过程
模块。而且您有两种使用它的主要方式。如果您只想调用程序并等待输出而不会捕获输出:
输出将在Stdout中打印,但您不会在Python变量中获得。
但是,您还可以使用其他参数指定不向用户显示输出。
如果要将输出存储在变量中:
编辑:在我的示例中,变量是
process_data
的参数A cleaner way to call an external program is to use python
subprocess
module. And you have two main way of using it.If you just want to call the program and wait for the output without catching it:
The output will be printed in stdout but you will not get it in a python variable.
However you can also specify not to show the output to the user using additional arguments.
If you want to store the output in a variable:
EDIT: in my example, variable is an argument to
process_data
, not the variable to store the output in解决方案在这里:
对于文本输出,我建议添加“ text = true”标志:
“ timeout = ...”标志是很好的
拥有 检查:
Solution is here:
In case of text output I'd recommend to add "text=True" flag:
It is good to have a "timeout=..." flag, in case your cmd is hung:
Don't forget to always check on: