Not because ...
You can not do this in a "Beautiful" way, a solution would be to turn off and on the USB output, but I'm pretty sure that OS will not let you do it that easy.
USB is fully dedicated to passing information, but on the cable you find + 5V and GND outputs for powering the plugged devices.
Controlling an electronic device by programming
First you need to understand electronics, at least the minimum (current, resistance..etc)
you can use a microcontroller or a circuit capable of communicating with a computer, nowadays Arduino has become the easiest platform and simple implementation of projects for lay developers, arduino can be programmed in java, c, python being the form adopted by the community.
Printing Data in the Serial Output
int pushButton = 2;
void setup() {
Serial.begin(9600);
// informa que pino "2" é uma entrada de dados
pinMode(pushButton, INPUT);
}
void loop() {
// faz a leitura da saida "2" do dispositivo
int buttonState = digitalRead(pushButton);
// Mostra isso na saida Serial
Serial.println(buttonState);
delay(1);
}
You can make your program communicate with another through the serial port.
Arduino communication with serial port in python
Python is a language with many facilitations, there is module for almost anything, including arduino, web, interfaces ...
#!/usr/bin/env python
"""
Blinks an LED on digital pin 13
in 1 second intervals
"""
from Arduino import Arduino
import time
board = Arduino('9600') #plugged in via USB, serial com at rate 9600
board.pinMode(13, "OUTPUT")
while True:
board.digitalWrite(13, "LOW")
time.sleep(1)
board.digitalWrite(13, "HIGH")
time.sleep(1)
Check out the documentation Python-Arduino