使用Python subprocess运行shell命令。

huangapple go评论116阅读模式
英文:

Run shell commands with Python subprocess

问题

I encountered a problem.
I want to run a command: leaks -atExit -- ./a.out < test.in | grep LEAK in subprocess in Python. But instead of input being passed with < test.in, I want to take it from a variable.
Please help.

In a different part of my code, I tried:

res = subprocess.run(['./a.out'], capture_output=True, text=True, input=self.input_text, check=True)

and it worked perfectly. But when I want to do it similarly,

res = subprocess.run(['leaks', '-atExit', '--', './a.out', '|', 'grep', 'LEAK'], capture_output=True, text=True, input=self.input_text, check=True)

It does not work.

英文:

i encountered a problem.
I want to run a command: leaks -atExit -- ./a.out &lt; test.in | grep LEAK in subprocess in Python. But instead of input beeing passed with &lt; test.in, I want to take it from variable.
Please help.

In the different part of my code, I tried:

res = subprocess.run([&#39;./a.out&#39;], capture_output=True, text=True, input=self.input_text, check=True)

and it worked perfecly. But when I want to do it simmilarly,

res = subprocess.run([&#39;leaks&#39;, &#39;-atExit&#39;, &#39;--&#39;, &#39;./a.out&#39;, &#39;|&#39;, &#39;grep&#39;,&#39; LEAK&#39;], capture_output=True, text=True, input=self.input_text, check=True)

It does not work.

答案1

得分: 1

我成功解决了我的问题。

command = 'leaks -atExit -- ./a.out <' + str(self.input_filepath) + '| grep LEAK'
res = subprocess.run(command, text=True, capture_output=True, shell=True)

工作了

英文:

I managed to resolve my problem.

command = &#39;leaks -atExit -- ./a.out &lt;&#39; + str(self.input_filepath) + &#39;| grep LEAK&#39;
   res = subprocess.run(command, text=True, capture_output=True, shell=True)

Worked

huangapple
  • 本文由 发表于 2023年6月1日 04:55:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/76377209.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定