Read/Write in Stdin/Stdout or PIPE [Top resolved]

Just starting out? Need help? Post your questions and find answers here.
User avatar
Kwai chang caine
Always Here
Always Here
Posts: 5494
Joined: Sun Nov 05, 2006 11:42 pm
Location: Lyon - France

Read/Write in Stdin/Stdout or PIPE [Top resolved]

Post by Kwai chang caine »

Hello at all

I have found my solution for remote a browser with PhantomJS
Unfortunately, since yesterday i try several code for read and write in a PIPE or Std

I have found one for read the PIPE of the create process, but i have two problem :

1/ Why Phantom finish alone ?
2/ How can i write in the PIPE created for send the command to Phantom

If someone can help me :oops:

http://www.sendbox.fr/7028587ab86c5c3b/phantomjs.exe

Code: Select all

Enumeration
 #Form0
 #EditorCommande
 #StringCommande
 #Bouton
EndEnumeration

Global pi.PROCESS_INFORMATION
Global hWritePipe.l,hReadPipe.l,PipeMem.l,PipeString.s
Global compx.l,last.s

PipeMem = AllocateMemory(1024)

Procedure GetOutPut()
 
 bytesread.l = 0
 o.l = 1023
 r.l = PeekNamedPipe_(hreadPipe,0,0,0,@bytesread,0)
 
 If bytesread > 0
 
  o.l = ReadFile_(hReadPipe,PipeMem,1023,@bytesread,0)
 
  For f.l=0 To bytesread
 
   t.b = PeekB(PipeMem+f)
 
   If t<>0
 
    u.b=PeekB(PipeMem+f+1)
    v.b=PeekB(PipeMem+f+1)
 
    If t=13
 
     Print(PipeString)
     PipeString=""
 
     If u=10 
      f+1
     EndIf                
 
    Else
 
     If t>31 And t<128 
      PipeString + Chr(t)
     EndIf
 
    EndIf
    
   EndIf
 
  Next
  
  AddGadgetItem(#EditorCommande, -1, PipeString)
 
 Else
 
  Delay(10)
 
 EndIf
 
EndProcedure

Procedure RunCommand(cmd.s)
 
 path.s=GetPathPart(cmd)
 sa.SECURITY_ATTRIBUTES
 sa\nLength=SizeOf(SECURITY_ATTRIBUTES)
 sa\bInheritHandle=1
 sa\lpSecurityDescriptor=0
 
 xx.l=CreatePipe_(@hReadPipe,@hWritePipe,@sa,1)
 
 si.STARTUPINFO
 si\cb=SizeOf(STARTUPINFO)
 si\dwFlags=#STARTF_USESTDHANDLES|#STARTF_USESHOWWINDOW
 si\hStdOutput=hWritePipe
 si\hStdError=hWritePipe
 Result = CreateProcess_(0,cmd,@sa,@sa,1,#CREATE_NO_WINDOW,0,path,@si,@pi)
 ProcedureReturn Result
 
EndProcedure

Procedure WaitProcess(*value)
 
 exitcode.l=259
 
 While exitcode=259
 
  t=GetExitCodeProcess_(pi\hProcess,@exitcode)
 
  If exitcode<>259
   ; We've Finished
  Else
   GetOutPut()
  EndIf
  
 Wend
 
 CloseHandle_(hWritePipe)
 
EndProcedure

PipeString=""
Application.s = Space(255) 
GetModuleFileName_(0, @Application, 255) 
CheminProgramme.s = GetPathPart(Application) 

OpenWindow(#Form0, 379, 176, 608, 542, "Remote PhantomJS", #PB_Window_SystemMenu|#PB_Window_SizeGadget|#PB_Window_TitleBar)
EditorGadget(#EditorCommande, 5, 15, 593, 447)
StringGadget(#StringCommande, 6, 469, 594, 23, "console.log('Hello, world!');")
ButtonGadget(#Bouton, 211, 503, 201, 33, "Send to Phantom")

If RunCommand(CheminProgramme + "phantomjs.exe")
 
 CreateThread(@WaitProcess(),0)
 
 Repeat  
  
  Evenement = WaitWindowEvent()
  EvenementGadget = EventGadget()
  EvenementType = EventType()
  
  If Evenement = #PB_Event_Gadget
   
   Select EvenementGadget
     
    Case #Bouton
     
     MessageRequester("Kcc", "How send the function in the StringGadget above, to the PIPE of phantom, please ?")
     
   EndSelect
   
  EndIf
  
 Until Evenement = #PB_Event_CloseWindow
 
Else
 
 Debug GetLastError_()
 
EndIf

Have a good day
Last edited by Kwai chang caine on Thu Feb 11, 2016 5:16 pm, edited 1 time in total.
ImageThe happiness is a road...
Not a destination
User avatar
Kwai chang caine
Always Here
Always Here
Posts: 5494
Joined: Sun Nov 05, 2006 11:42 pm
Location: Lyon - France

Re: Read/Write in Stdin/Stdout or PIPE

Post by Kwai chang caine »

Nobody can or want answer :|
Then.... just a little question perhaps... :oops:

Is it possible to run an exe with runprogram or createprocess, and write or read/write in his pipe or stdin/out during all the time that the exe run ??

Because i have also try with the fred code runprogram, readstringprogram, writestringprogram and i can't communicate permanently with phantomjs :(
ImageThe happiness is a road...
Not a destination
Marc56us
Addict
Addict
Posts: 1600
Joined: Sat Feb 08, 2014 3:26 pm

Re: Read/Write in Stdin/Stdout or PIPE

Post by Marc56us »

Hi KCC,

If I followed (the different topics that you open), what you want to do ultimately is to automate a dialogue via a browser?
There are very effective programs for it (about $ 60)

-- Fr
Si j'ai bien suivi (les différents topics que tu as ouverts), ce que tu veux faire au final est d'automatiser un dialogue via un navigateur ?
Il existe des outils très efficaces pour cela. (non, ce n'est pas autoit)
Les applications web ont la particularité de brouiller volontairement leur code source le plus souvent pour imposer leurs pubs, donc chercher à automatiser via le code source de la page est ch... et souvent presque impossible.
La meilleure manière d'automatiser est donc de mimer le comportement humain en utilisant la reconnaissance d'images, mais pas simplement des morceaux de copie écran: Un outils élaboré sait non seulement comparer des images (sur l'écran ou en mémoire vidéo), mais le faire avec un certain degré de tolérance tant au niveau pixels que % de correspondance (ce qui lui permet de voir un bouton existant grisé ou non par exemple). Il sait aussi utiliser des masques, ce qui permet d'exclure des zones variables (par exemple des coches sur des images).

C'est un outil d'automatisation utilisé aussi comme outil de test. (Programme commercial, donc je ne le cite pas ici)

:)
User avatar
Kwai chang caine
Always Here
Always Here
Posts: 5494
Joined: Sun Nov 05, 2006 11:42 pm
Location: Lyon - France

Re: Read/Write in Stdin/Stdout or PIPE

Post by Kwai chang caine »

Hello Mar56UnitedState :wink:
Glad to talk to you 8)

Yes, they are numerous years i turn around the subject of remoting browser without 100% of succes :cry:
Before i use, OLE and IE, and that's works nearly good
But now, IE is always to late, and not always good updating on all machines

So i try Firefox, all advantage (Portable, last version, add-on, etc...)
But remote FF, is not also simple than IE because not OLE

So, since several years, i try all the ways for do this job
Before, i try SELENIUM, but OOP and i cannot using it directly with PB :cry:
And lastly, i see PhantomJS...exactely what i want :D
Only one executable, open source
But for the moment not really kind with KCC and PB :?

Other, i know one program, who recognize part of the webrowser by cut little pictures
But i search a more professional method, it's for my office :wink:
So thanks for your advice 8)

"FRANCHE" :mrgreen:
Oui j'ai croisé ce genre de programme
On prenait des portions de la page en capture et il se chargeait de les retrouver
Y'a même un code de ouf sur ce forum qui fait ça, j'ai essayé de l'utiliser mais pour la recherche de toute une page il etait trop long :cry:
Mais, je cherche un truc un peu plus "top moumoute" pour mon boulot :wink:

En attendant SELENIUM est vraiment cool, je l'ai essayé il trouve même des balises grace à leur PATH :shock:
Il est juste compliqué à programmer car POO et PYTHON sous ses allures simples, ne l'est pas tant que ça :?

C'est un truc de guedin..... :? y'a whatmilles codes de oufs pour utiliser les PIPES, les STD et tout le toutim...
Et pas un ne marche vraiment pour un EXE non PB, sauf la lecture à la creation du process
A croire que une fois lancé, on peut plus causer avec l'EXE
Remarque peut être que c'est pas prevu .....
Y'a des codes qui pilotent la console, mais pour ce qui est de piloter un EXE non PB, c'est le désert de gergovie..

Quoi qu'il en soit merci de ton avis, car je me sent un peu seul sur cette action 8)
ImageThe happiness is a road...
Not a destination
infratec
Always Here
Always Here
Posts: 7618
Joined: Sun Sep 07, 2008 12:45 pm
Location: Germany

Re: Read/Write in Stdin/Stdout or PIPE

Post by infratec »

Hi KCC,

I thought I found a working solution, but it works only 25% of the time :!:
So I have to investigate it a bit more...

Bernd
infratec
Always Here
Always Here
Posts: 7618
Joined: Sun Sep 07, 2008 12:45 pm
Location: Germany

Re: Read/Write in Stdin/Stdout or PIPE

Post by infratec »

Got it:

Code: Select all

CompilerIf Not #PB_Compiler_Thread
  MessageRequester("Info", "Enable Thread-Safe in compiler options!")
  End
CompilerEndIf



Enumeration
  #Form0
  #EditorCommande
  #StringCommande
  #Bouton
EndEnumeration

Enumeration #PB_Event_FirstCustomValue
  #Own_Event_FromProg
  #Own_Event_Exit
EndEnumeration


Structure ThreadParameterStructure
  Semaphore.i
  Thread.i
  ProgramID.i
  FromProg$
  ToProg$
  Exit.i
EndStructure





Procedure HandleIO(*ThreadParameter.ThreadParameterStructure)
  
  Protected ReadLen.i, WriteLen.i, Error$
  
  *Buffer = AllocateMemory(1024)
  
  If *Buffer
    
    *ThreadParameter\ProgramID = RunProgram("phantomjs.exe", "", "", #PB_Program_Open|#PB_Program_Read|#PB_Program_Write|#PB_Program_Error|#PB_Program_UTF8|#PB_Program_Hide)
    
    If *ThreadParameter\ProgramID
      
      Repeat
        
        ReadLen = AvailableProgramOutput(*ThreadParameter\ProgramID)
        If ReadLen
          ReadLen = ReadProgramData(*ThreadParameter\ProgramID, *Buffer, ReadLen)
          If ReadLen
            *ThreadParameter\FromProg$ = PeekS(*Buffer, ReadLen, #PB_UTF8)
            PostEvent(#Own_Event_FromProg)
            WaitSemaphore(*ThreadParameter\Semaphore)
          EndIf
        EndIf
        
        Error$ = ReadProgramError(*ThreadParameter\ProgramID, #PB_UTF8)
        If Len(Error$)
          *ThreadParameter\FromProg$ = Error$
          PostEvent(#Own_Event_FromProg)
          WaitSemaphore(*ThreadParameter\Semaphore)
        EndIf
        
        If Len(*ThreadParameter\ToProg$)
          *ThreadParameter\ToProg$ + #CRLF$
          WriteLen = PokeS(*Buffer, *ThreadParameter\ToProg$, -1, #PB_UTF8)
          *ThreadParameter\ToProg$ = ""
          WriteLen = WriteProgramData(*ThreadParameter\ProgramID, *Buffer, WriteLen)
          SignalSemaphore(*ThreadParameter\Semaphore)
        EndIf
        
        Delay(10)
        
      Until *ThreadParameter\Exit Or Not ProgramRunning(*ThreadParameter\ProgramID)
      
      CloseProgram(*ThreadParameter\ProgramID)
      
    EndIf
    
    FreeMemory(*Buffer)
  EndIf
  
  PostEvent(#Own_Event_Exit)
  
EndProcedure




Define Event.i, Exit.i
Define ThreadParameter.ThreadParameterStructure

;OpenConsole()

OpenWindow(#Form0, 379, 176, 608, 542, "Remote PhantomJS", #PB_Window_SystemMenu|#PB_Window_SizeGadget|#PB_Window_TitleBar)
EditorGadget(#EditorCommande, 5, 15, 593, 447)
StringGadget(#StringCommande, 6, 469, 594, 23, "console.log('Hello, world!');")
ButtonGadget(#Bouton, 211, 503, 201, 33, "Send to Phantom")


ThreadParameter\Semaphore = CreateSemaphore()
ThreadParameter\Thread = CreateThread(@HandleIO(), @ThreadParameter)

Repeat
  
  Event = WaitWindowEvent()
  
  Select Event
    Case #Own_Event_FromProg
      AddGadgetItem(#EditorCommande, -1, ThreadParameter\FromProg$)
      SignalSemaphore(ThreadParameter\Semaphore)
      
    Case #Own_Event_Exit
      Exit = #True
      
    Case #PB_Event_Gadget
      Select EventGadget()
        Case #Bouton
          ThreadParameter\ToProg$ = GetGadgetText(#StringCommande)
          WaitSemaphore(ThreadParameter\Semaphore)
      EndSelect
      
    Case #PB_Event_CloseWindow
      If IsThread(ThreadParameter\Thread)
        ;CloseProgram(ThreadParameter\ProgramID)
      EndIf
      FreeSemaphore(ThreadParameter\Semaphore)
      Exit = #True
  EndSelect
  
Until Exit
Bernd
infratec
Always Here
Always Here
Posts: 7618
Joined: Sun Sep 07, 2008 12:45 pm
Location: Germany

Re: Read/Write in Stdin/Stdout or PIPE

Post by infratec »

Added a Delay(10) above to avoid high CPU load.
User avatar
Kwai chang caine
Always Here
Always Here
Posts: 5494
Joined: Sun Nov 05, 2006 11:42 pm
Location: Lyon - France

Re: Read/Write in Stdin/Stdout or PIPE

Post by Kwai chang caine »

Hello my friend INFRATEC !!!! :D

it's been several days that I felt alone , me and my phantomJS :(
And see it's not only the JS, but also the help must be a Phantom :oops:

Very sad, i open my webbrowser on my favorite blue page...and what i see...my subject at the begin with a little yellow icon :shock:
I look in the right side, and see another time the name of my saver INFRATEC 8)
you never will imagine how you cheers me

I put your splendid code into my IDE and the miracle appears !!!
That's works very well 8) 8)

Never i believe, an also complex code it necessary :shock:
Without you, never i can create it :oops:

I know now, why i don't have answers, because it's very difficult to remote an EXE with his STDIN :?

Never i can thank you, your code allow me to manage several EXE, when DLL not exist or if the code is OOP

Again thank you very much, from background of my heart 8) 8)

Kcc is happy and go immediately play with his new toy :mrgreen:
I love you....
Your french fan

Kcc
ImageThe happiness is a road...
Not a destination
peekpoke
New User
New User
Posts: 1
Joined: Thu Feb 16, 2017 5:44 pm
Location: L'viv Ukraine

Re: Read/Write in Stdin/Stdout or PIPE [Top resolved]

Post by peekpoke »

Hello.
Really I liked this program.
I do have a question:
How to modify this program to run the console - OpenConsole() (for StdIn / StdOut) rather than RunProgram("phantomjs.exe").
I dream to launch this another program instead of phantomjs.ehe and talk to her through the pipe StdIO.
That is, this program have to run a modified version of itself(with OpenConsole() only), and be able to exchange messages.
I do not have enough knowledge of purebasic language.
That's what I want to do and to understand how it have to be done.
Help me please.
Post Reply