如何将来自 bash 的数据流与 python 中的子进程一起使用
How to use data stream from bash with subprocess in python
我正在尝试调用 linux bash 中的进程,使用数据流信号“<”将文件用作应用程序的输入。
但是,此应用程序不接收来自文件的输入。
我正在使用这个:
#the application do not receives data stream from file
command = './grid < /home/felipe/Documents/proteins/grid.in'.split(' ')
p = subprocess.Popen(command,stdout=subprocess.PIPE)
但它不起作用,例如 os.system(),它做了我想用子进程做的事情:
#works
command = './grid < /home/felipe/Documents/proteins/grid.in'.split(' ')
os.system(command)
如何将数据流信号“<”与子进程模块一起使用以获取应用程序的输入?
如果您只想将 Python 用作 shell 包装器,则必须使用 shell=True
启动您的(子)进程。但是由于您已经在使用 Python,您可能希望更多地依赖 Python 而更少地依赖 shell,您可以执行以下操作:
with open('/home/felipe/Documents/proteins/grid.in') as in_file:
p = subprocess.Popen('./grid', stdin=in_file)
这将以 in_file
形式打开您的输入文件,并将其输入 ./grid
的标准输入,就像 shell 重定向一样。
我正在尝试调用 linux bash 中的进程,使用数据流信号“<”将文件用作应用程序的输入。
但是,此应用程序不接收来自文件的输入。 我正在使用这个:
#the application do not receives data stream from file
command = './grid < /home/felipe/Documents/proteins/grid.in'.split(' ')
p = subprocess.Popen(command,stdout=subprocess.PIPE)
但它不起作用,例如 os.system(),它做了我想用子进程做的事情:
#works
command = './grid < /home/felipe/Documents/proteins/grid.in'.split(' ')
os.system(command)
如何将数据流信号“<”与子进程模块一起使用以获取应用程序的输入?
如果您只想将 Python 用作 shell 包装器,则必须使用 shell=True
启动您的(子)进程。但是由于您已经在使用 Python,您可能希望更多地依赖 Python 而更少地依赖 shell,您可以执行以下操作:
with open('/home/felipe/Documents/proteins/grid.in') as in_file:
p = subprocess.Popen('./grid', stdin=in_file)
这将以 in_file
形式打开您的输入文件,并将其输入 ./grid
的标准输入,就像 shell 重定向一样。