【发布时间】:2016-01-14 17:11:30
【问题描述】:
我是编程新手,一直在努力解决这个问题......
我正在编写一个 Python 脚本来自动化基于交互式命令行的 Perl 脚本,以便它可以在指定目录中的每个文件上运行。我可以使用subprocess.call 和subprocess.Popen 启动程序,但是从那里我要么打开程序,它就在那里等待用户输入,要么我打开它无限次。我需要 Perl 脚本为每个文件打开一次,接受用户输入(当然,在每次输入后按下类似于“enter”的东西,以及一个包含文件名的命令,在示例中应该是 str(files)下面的代码),使用用户输入"4" 开始 Perl 脚本的计算,然后关闭它。
我知道这是可能的,但我尝试了 1000 种不同的方法都无济于事。有人可以给我一个“像我 5 岁一样解释它”,如何让这个 Python 和 Perl 脚本像用户输入命令一样相互交谈?
这是我目前所拥有的:
for files in os.listdir("In_Files"):
print "Performing calculations on " + str(files) + " ..."
os.chdir("/home/MTS/Dropbox/dir/In_Filess")
subprocess.Popen("run_command.command -f a", shell=True) #this boots up the Perl script
time.sleep(3) #waits for the script to open...
Popen.communicate(input="1") #user inputs begin here
Popen.wait(0) #am I trying to set a return value here so that the inputs may proceed once the previous one has been accepted?
Popen.communicate(input=str(files)) #this is where the name of the file the Perl script is working on is entered
Popen.wait(0)
Popen.communicate(input="4")
Popen.wait(0)
我一直在阅读很多关于标准输入管道的文章,但不太了解它们。它们是用于解决这个问题还是应该使用其他方法?另外,我已经查看了 Pexpect,但这似乎不起作用。
非常感谢您的帮助。
【问题讨论】:
-
当我想做这种事情时,我会在 shell 级别使用管道。
-
您是只想将数据发送到子进程还是要从中读取数据?
-
您确实意识到 Perl 程序可能会意识到它没有附加到 tty 并期望使用不同的格式,对吧?编辑 Perl 程序可能更容易
-
多亏了这里发布的建议,我已经弄清楚了。结果(如我所料)我并不完全了解如何向 Perl 程序发送通信。
标签: python perl subprocess