Categories
PHP

Running a PHP Script as Daemon

For our ongoing project at Leevio, I had to find a way to run a php script as a daemon. I checked out a few techniques. I didn’t like any of them much. I needed a way to run the intended script and then exit the terminal leaving the script to keep running in the background.

After a bit of hard work, I chose to use the PCNTL functions to achieve my goal. Here’s the code I used:

Note that, in this case, the daemon quits the moment the shell_exec() command is executed. We are executing our intended PHP script as a sub process which has been detached from the terminal. The script has a while loop to keep it running forever. So, we can safely quit the main process while the forked process remains alive with the php script being executed 😀

Categories
Python

Python: Printing without newline or space :)

While coding in Python, I have seen that the Print statement adds a newline to it’s output which is very helpful in most cases. While I have to add a newline character manually in PHP, I have to type less in Python. I used to love this feature until I faced a situation when I have to print out data without any newline character or space. I finally found out the solution 🙂 I have to write the characters of a string manually to stdout using the “sys” module.

Have a look at the following codes:

As you can see, I have defined a function masnun_print() that prints out it’s default argument without space just like the echo statement in PHP. To give a line break between the “Hello World!” and the “1 to 100 series”, we have manually printed out newline character 🙂

Categories
PHP Python

Handling Exceptions in PHP and Python

It’s really a very important programming practice to properly handle any possible exceptions… It makes the code more stable, efficient and re-usable.

PHP:
PHP now has a very good exception handling mechanism. Just put a “try” block and then “catch ” the exception if anything goes wrong 🙂

Have a look at the following code:

The code is self explanatory. But you must use the “Exception” word before $e in the catch block to get things going perfectly. Like I did, you can “throw” a new exception in case there was really something unexpected in your code 🙂

Python:
Python is just a fantastic language. Here’s the Python equivalent of the above code snippet:

The only difference in PHP and Python’s exception handling is it’s language structure. In Python, we don’t throw an exception, rather we raise one. Just a bit of politeness! 😉

Conclusion:
Both PHP and Python has very good exception handling techniques. I can’t discuss them all on this blog but you should consult the respective manuals to master them. They are really very essential! 😀