I am trying to run an MQTT client that receives and publishes messages at the same time. What I am trying to do is to stop the while loop responsible for publishing when I receive a message. But running never becomes False for the while loop and the loop is never broken. What should I do? I just want to break the loop when a message is received. Here's my code:  running = True def on_message(client, userdata, msg):      print(msg)      running = False      print(running) # it becomes False here  client.on_connect = on_connect client.on_message = on_message client.connect(HOST, 1883, 60)  client.loop_start() # used to receive on_message events while the while loop is true   while running:     #publish and do something until running is False
4613
How can I create or use a global variable in a function?  If I create a global variable in one function, how can I use that global variable in another function? Do I need to store the global variable in a local variable of the function which needs its access?
47535
How can I poll the keyboard from a console python app?  Specifically, I would like to do something akin to this in the midst of a lot of other I/O activities (socket selects, serial port access, etc.):     while 1:       # doing amazing pythonic embedded stuff       # ...        # periodically do a non-blocking check to see if       # we are being told to do something else       x = keyboard.read(1000, timeout = 0)        if len(x):           # ok, some key got pressed           # do something   What is the correct pythonic way to do this on Windows?  Also, portability to Linux wouldn't be bad, though it's not required.
47297
I have a program that receives an argument and prints it every second:    ~# ./myapp 234 234 234 234 234 ...     I want to be able to run it in the background and right after a shell but it must be in one line (I don't want to explain why I need it because I don't want to make the discussion too complicated right now).    This is what I tried and the error I received:    ~# bash -c "./myapp 234 &amp;; sh"  bash: -c: line 0: syntax error near unexpected token `;' bash: -c: line 0: `./myapp 234 &amp;; sh'   I also tried with &amp;&amp; as separator:    ~# bash -c "./myapp 234 &amp; &amp;&amp; sh"  bash: -c: line 0: syntax error near unexpected token `&amp;&amp;' bash: -c: line 0: `./myapp 234 &amp; &amp;&amp; sh'   Any idea how I can solve it?    EDIT: Thanks to @roaima. I also found a link that talks about it:
42795
How do i tell if one instance of my program is running? I thought I  could do this with a data file but it would just be messy :(  I want to do this as I only want 1 instance to ever be open at one point.
15102
What can I do to configure SSH on both client and servers to prevent Write Failed: broken pipe errors? It often occurs if you sleep your client computer and resume later.
33475
There is a yes command in unix/linux which basically infinitely prints y to the stdout. What is the point of it, and how is it useful?
51062
Does it mean that two threads can't change the underlying data simultaneously? Or does it mean that the given code segment will run with predictable results when multiple threads are executing that code segment?
35834
I ran this command to try and get my python program to run in the background and let me exit the SSH connection I am using:  nohup python files.py &gt;&gt; files.log &amp;   I then check ps to check it worked   $ ps a   PID TTY      STAT   TIME COMMAND 13059 pts/0    Ss     0:00 -bash 13327 pts/0    R+     0:00 ps a [1]+  Exit 1                  nohup python files.py &gt;&gt; files.log   What does this [1]+  Exit 1 mean?  And how can I run my program in the background letting me exit correctly?
95856
I have some Python code that works correctly when I use python.exe to run it, but fails if I use pythonw.exe.       def runStuff(commandLine):         outputFileName = 'somefile.txt'         outputFile = open(outputFileName, "w")          try:             result = subprocess.call(commandLine, shell=True, stdout=outputFile)         except:             print 'Exception thrown:', str(sys.exc_info()[1])      myThread = threading.Thread(None, target=runStuff, commandLine=['whatever...'])     myThread.start()   The message I get is:       Exception thrown: [Error 6] The handle is invalid   However, if I don't specify the 'stdout' parameter, subprocess.call() starts okay.  I can see that pythonw.exe might be redirecting output itself, but I can't see why I'm blocked from specifying stdout for a new thread.
74382
i have:  for i in range(2,n):     if(something):        do something     else:        do something else        i = 2 **restart the loop   But that doesn't seem to work. Is there a way to restart that loop?   Thanks
60594
I want to try simple script  flag=false while !$flag do    read x    if [ "$x" -eq "true" ]    then      flag=true    fi    echo "${x} : ${flag}" done   But when I run it, if I type true, I will see that x="true" and flag="true", but the cycle doesn't end. What is wrong with the script? How can I properly invert a boolean variable?
43611
On Windows, you can set what should happen if/when a service fails.  Is there a standard way of achieving the same thing on Linux (CentOS in particular)?  A bigger part of my question is: how do you handle sockets that have been left open - for example in TIME_WAIT, FIN_WAIT1, etc states.  At the moment if the service I am developing crashes, I have to wait for the sockets to clear or change the listen port before I can then manually restart it.  Thanks for your help.
96984
Consider the following script:  #!/bin/bash  set -o pipefail set -o history  trapper() {    func="$1" ; shift    for sig ; do       trap "$func $sig" "$sig"    done }  err_handler () {   case $2 in     INT)        stop_received=1     ;;     TSTP)     ;;     ERR)        if [[ $2 != "INT" ]]; then # for some reason, ERR gets triggered on SIGINT           code=$?           if [ $code -ne 0 ]; then              echo "Failed on line $1"              echo "$BASH_COMMAND returned $?"              echo "Content of variables at the time of failure:"              echo "$(set -o posix; set)"              exit 1           fi        fi     ;;   esac }  main() {    ping -c 5 www.google.com # this is a test to see if INT interrupts main()    # do a bunch of stuff, I mean a real bunch of stuff, like check some    # files, do some processing, connect to a database,    # do more processing, move some files around, you get the drift }  exec &gt; &gt;(tee -a my.log) exec 2&gt;&amp;1  trapper 'err_handler $LINENO' INT TSTP ERR while main do   if [[ "$stop_received" == "1" ]]; then      break   fi   setsid sleep 2 &amp; wait done trap ERR   What I am trying to accomplish is to run the script in an infinite loop until either the function main() returns some non zero value, i.e. some error occurred, or SIGINT is received.  However, I don't want SIGINT to stop main() from executing, in other words, if the script receives a SIGINT, it should wait for main() to finish, then exit nicely. But when I hit CTRL+C, I can see that ping is interrupted. At the moment I commented out everything under main() just to see if this works. Since ping gets interrupted, I am assuming other commands under main() would also get interrupted. When ping is interrupted, the processing jumps to the line where I check if $stop_received=1 and then the loop breaks and the script quits. If I replace the break with just an echo, then the script just continues on to the next iteration of the while main loop.  How can I stop SIGINT from interrupting the currently running command(s)? Since my script does a bunch of stuff, including DML statements in a database, interrupting main() would cause lot of grief.  Secondly, the script does not trap ctrl+z either. Or rather, the script just gets stuck on ctrl+z requiring a kill pid to terminate. I assumed that sleep being a child of bash as opposed to the script itself, ctrl+z would cause the script to pause, leaving sleep in limbo land. Hence the setsid and wait on sleep, but it still hangs.  thanks.
32016
I am stuck on a few issues in . (Note: It is at the frame concerning this question.)  In it, from what I understand (which could be wrong) we first apply the Hadamard gate to a qbit in the $\lvert 0 \rangle$ state. Then on that we use a controlled not on the output value, together with another input from another qbit set at $\lvert 0 \rangle$. I don't understand how to work this out and how the $\lvert 00 \rangle + \lvert 10 \rangle$ is derived for the output of combination of the two gates.  Here is what I am thinking (neglecting the $1/\sqrt{2}$ multiplier):  $$ \begin{pmatrix} 1 &amp; 1 \\ 1 &amp; -1 \end{pmatrix} \begin{pmatrix} 1 \\ 0 \end{pmatrix} = \begin{pmatrix} 1 \\ 1 \end{pmatrix} = \begin{pmatrix} 1 \\ 0 \end{pmatrix} + \begin{pmatrix} 0 \\ 1 \end{pmatrix} = \lvert 0 \rangle + \lvert 1 \rangle. $$  There however is another $\lvert 0 \rangle$ coming in from the second (bottom) wire and it interacts with the output from the Hadamard gate. I don't understand how to manipulate the values - have no idea if I can do something such as the following by distribution: $$ (\lvert 0 \rangle + \lvert 1 \rangle) \lvert 0 \rangle = \lvert 0 \rangle \lvert 0 \rangle + \lvert 1 \rangle \lvert 0\rangle. $$  I have no idea why we can do this (if we can even do so), but this is the only way I can see that we could get $\lvert 0 \rangle \lvert 0 \rangle + \lvert 1\rangle \lvert 0 \rangle = \lvert 00 \rangle + \lvert 10 \rangle$, as the author of the video has on the particular time in the video.  Any clarification would be extremely appreciated.
37170
My little brother is just getting into programming, and for his Science Fair project, he's doing a simulation of a flock of birds in the sky. He's gotten most of his code written, and it works nicely, but the birds need to move every moment.  Tkinter, however, hogs the time for its own event loop, and so his code won't run. Doing root.mainloop() runs, runs, and keeps running, and the only thing it runs is the event handlers.  Is there a way to have his code run alongside the mainloop (without multithreading, it's confusing and this should be kept simple), and if so, what is it?  Right now, he came up with an ugly hack, tying his move() function to &lt;b1-motion&gt;, so that as long as he holds the button down and wiggles the mouse, it works. But there's got to be a better way.
649
As a follow up to a , I wonder why it is impossible in Java, without attempting reading/writing on a TCP socket, to detect that the socket has been gracefully closed by the peer? This seems to be the case regardless of whether one uses the pre-NIO Socket or the NIO SocketChannel.  When a peer gracefully closes a TCP connection, the TCP stacks on both sides of the connection know about the fact. The server-side (the one that initiates the shutdown) ends up in state FIN_WAIT2, whereas the client-side (the one that does not explicitly respond to the shutdown) ends up in state CLOSE_WAIT. Why isn't there a method in Socket or SocketChannel that can query the TCP stack to see whether the underlying TCP connection has been terminated? Is it that the TCP stack doesn't provide such status information? Or is it a design decision to avoid a costly call into the kernel?  With the help of the users who have already posted some answers to this question, I think I see where the issue might be coming from. The side that doesn't explicitly close the connection ends up in TCP state CLOSE_WAIT meaning that the connection is in the process of shutting down and waits for the side to issue its own CLOSE operation. I suppose it's fair enough that isConnected returns true and isClosed returns false, but why isn't there something like isClosing?  Below are the test classes that use pre-NIO sockets. But identical results are obtained using NIO.  import java.net.ServerSocket; import java.net.Socket;  public class MyServer {   public static void main(String[] args) throws Exception {     final ServerSocket ss = new ServerSocket(12345);     final Socket cs = ss.accept();     System.out.println("Accepted connection");     Thread.sleep(5000);     cs.close();     System.out.println("Closed connection");     ss.close();     Thread.sleep(100000);   } }   import java.net.Socket;  public class MyClient {   public static void main(String[] args) throws Exception {     final Socket s = new Socket("localhost", 12345);     for (int i = 0; i &lt; 10; i++) {       System.out.println("connected: " + s.isConnected() +          ", closed: " + s.isClosed());       Thread.sleep(1000);     }     Thread.sleep(100000);   } }   When the test client connects to the test server the output remains unchanged even after the server initiates the shutdown of the connection:  connected: true, closed: false connected: true, closed: false ...
79808
Consider the interactive program interactive. I have to run this program fairly frequently, and each time I run it the first few commands are the same. Obviously, having to type those commands over and over again is a pain. I have collected those command (separated by newlines) in the file cmd. Now I can do cat cmd | interactive to run the commands. The problem is that once cmd has been fully read, interactive recieves EOF and exits.  What I wish to do is first have interactive read from the pipe (obviously interactive &lt; cmd is also acceptable) and when EOF is received, start reading from the keyboard instead.