[英]How to run an inline shell script from python?
I have a small shell script in a string inside my python file. 我的python文件中的字符串中有一个小的Shell脚本。
Now I'd like to run this script via subprocess.call()
and I wonder what's the best way. 现在,我想通过subprocess.call()
运行此脚本,我想知道什么是最好的方法。
My first thought was to write the script to a StringIO
and specify that via stdin=...
but unfortunately you cannot specify a StringIO
since it doesn't have a fileno()
method. 我的第一个想法是将脚本写入StringIO
并通过stdin=...
指定,但是很遗憾,您无法指定StringIO
因为它没有fileno()
方法。
Of course I could use stdin=subprocess.PIPE
and then write to it using subprocess.communicate()
but I wonder if there's a simpler method. 当然,我可以使用stdin=subprocess.PIPE
,然后使用subprocess.communicate()
对其进行写入,但我想知道是否有更简单的方法。
import subprocess
script = """
for x in 1 2 3 ; do echo $x ; sleep 1 ; done
"""
subprocess.call(['sh', '-c', script])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.