Can't run my Python script with two functions inside











up vote
4
down vote

favorite












I want to create a Python app where some data is retrieved and charted on a Dash app.



This is the Dash part. This is where my whole data will be sent and shown on a webpage, since I'm starting now, this is just a basic example of a live chart.



main.py



import dash
from dash.dependencies import Output, Event
import dash_core_components as dcc
import dash_html_components as html
import plotly
import random
import plotly.graph_objs as go
from collections import deque

app = dash.Dash(__name__)
app.layout = html.Div(
[
dcc.Graph(id='live-graph', animate=True),
dcc.Interval(
id='graph-update',
interval=1*1000
),
]
)

@app.callback(Output('live-graph', 'figure'),
events=[Event('graph-update', 'interval')])
def update_graph_scatter():
X.append(X[-1]+1)
Y.append(Y[-1]+Y[-1]*random.uniform(-0.1,0.1))

data = plotly.graph_objs.Scatter(
x=list(X),
y=list(Y),
name='Scatter',
mode= 'lines+markers'
)

return {'data': [data],'layout' : go.Layout(xaxis=dict(range=[min(X),max(X)]), yaxis=dict(range=[min(Y),max(Y)]),)}

if __name__ == '__main__':
app.run_server(debug=True)


This is the Python part where the data is retrieved, connecting to a Websocket.
data.py



import websocket
import json
from bitmex_websocket import Instrument
from bitmex_websocket.constants import InstrumentChannels
from bitmex_websocket.constants import Channels

websocket.enableTrace(True)

channels = [
InstrumentChannels.trade,
]

XBTUSD = Instrument(symbol='XBTUSD',
channels=channels)
XBTUSD.on('action', lambda msg: test(msg))

XBTUSD = Instrument(symbol='XBTUSD',
channels=channels)

XBTUSD.on('action', lambda msg: rekter(msg))

def rekter(msg):

if msg['table'] =='trade':
Rate = msg['data'][0]['price']

print(Rate)


XBTUSD.run_forever()


I tried to accomplish that by using imports, so I imported as a module my script, but that didn't work either:



from trades import XBTUSD
import dash
from dash.dependencies import Output, Event
import dash_core_components as dcc
import dash_html_components as html
import plotly
import random
import plotly.graph_objs as go
from collections import deque


X = deque(maxlen=2000)
X.append(1)
Y = deque(maxlen=2000)
Y.append(1)


app = dash.Dash(__name__)
app.layout = html.Div(
[
dcc.Graph(id='live-graph', animate=True),
dcc.Interval(
id='graph-update',
interval=1*1000
),
]
)

@app.callback(Output('live-graph', 'figure'),
events=[Event('graph-update', 'interval')])
def update_graph_scatter():
X.append(X[-1]+1)
Y.append(Y[-1]+Y[-1]*random.uniform(-0.1,0.1))

data = plotly.graph_objs.Scatter(
x=list(X),
y=list(Y),
name='Scatter',
mode= 'lines+markers'
)

return {'data': [data],'layout' : go.Layout(xaxis=dict(range=[min(X),max(X)]),
yaxis=dict(range=[min(Y),max(Y)]),)}



if __name__ == '__main__':
app.run_server(debug=True)

XBTUSD.run_forever()


Other than that, I tried turning it into modules, but it didn't work either.



My problem is that I don't know how to "embed" my second part into the first part. I tried do that, but if I put the lineXBTUSD.run_forever()before app.run_server(debug=True) only one part of the code will be executed and my whole Dash app won't run until I stop the first part of the code. Same happens if I do the opposite.



So the problem is XBTUSD.run_forever(), but I can't just remove that line because it won't run data.py. Is there a way to solve this?



I am now thinking of running two separated scripts with one sending data to a DB and the other one should query the DB, retrieve the data and chart it, but I don't know if it's the best solution because a) I'll be handling a lot of data every minute b) I don't know if it'll work when deployed online (on heroku, for example)










share|improve this question




























    up vote
    4
    down vote

    favorite












    I want to create a Python app where some data is retrieved and charted on a Dash app.



    This is the Dash part. This is where my whole data will be sent and shown on a webpage, since I'm starting now, this is just a basic example of a live chart.



    main.py



    import dash
    from dash.dependencies import Output, Event
    import dash_core_components as dcc
    import dash_html_components as html
    import plotly
    import random
    import plotly.graph_objs as go
    from collections import deque

    app = dash.Dash(__name__)
    app.layout = html.Div(
    [
    dcc.Graph(id='live-graph', animate=True),
    dcc.Interval(
    id='graph-update',
    interval=1*1000
    ),
    ]
    )

    @app.callback(Output('live-graph', 'figure'),
    events=[Event('graph-update', 'interval')])
    def update_graph_scatter():
    X.append(X[-1]+1)
    Y.append(Y[-1]+Y[-1]*random.uniform(-0.1,0.1))

    data = plotly.graph_objs.Scatter(
    x=list(X),
    y=list(Y),
    name='Scatter',
    mode= 'lines+markers'
    )

    return {'data': [data],'layout' : go.Layout(xaxis=dict(range=[min(X),max(X)]), yaxis=dict(range=[min(Y),max(Y)]),)}

    if __name__ == '__main__':
    app.run_server(debug=True)


    This is the Python part where the data is retrieved, connecting to a Websocket.
    data.py



    import websocket
    import json
    from bitmex_websocket import Instrument
    from bitmex_websocket.constants import InstrumentChannels
    from bitmex_websocket.constants import Channels

    websocket.enableTrace(True)

    channels = [
    InstrumentChannels.trade,
    ]

    XBTUSD = Instrument(symbol='XBTUSD',
    channels=channels)
    XBTUSD.on('action', lambda msg: test(msg))

    XBTUSD = Instrument(symbol='XBTUSD',
    channels=channels)

    XBTUSD.on('action', lambda msg: rekter(msg))

    def rekter(msg):

    if msg['table'] =='trade':
    Rate = msg['data'][0]['price']

    print(Rate)


    XBTUSD.run_forever()


    I tried to accomplish that by using imports, so I imported as a module my script, but that didn't work either:



    from trades import XBTUSD
    import dash
    from dash.dependencies import Output, Event
    import dash_core_components as dcc
    import dash_html_components as html
    import plotly
    import random
    import plotly.graph_objs as go
    from collections import deque


    X = deque(maxlen=2000)
    X.append(1)
    Y = deque(maxlen=2000)
    Y.append(1)


    app = dash.Dash(__name__)
    app.layout = html.Div(
    [
    dcc.Graph(id='live-graph', animate=True),
    dcc.Interval(
    id='graph-update',
    interval=1*1000
    ),
    ]
    )

    @app.callback(Output('live-graph', 'figure'),
    events=[Event('graph-update', 'interval')])
    def update_graph_scatter():
    X.append(X[-1]+1)
    Y.append(Y[-1]+Y[-1]*random.uniform(-0.1,0.1))

    data = plotly.graph_objs.Scatter(
    x=list(X),
    y=list(Y),
    name='Scatter',
    mode= 'lines+markers'
    )

    return {'data': [data],'layout' : go.Layout(xaxis=dict(range=[min(X),max(X)]),
    yaxis=dict(range=[min(Y),max(Y)]),)}



    if __name__ == '__main__':
    app.run_server(debug=True)

    XBTUSD.run_forever()


    Other than that, I tried turning it into modules, but it didn't work either.



    My problem is that I don't know how to "embed" my second part into the first part. I tried do that, but if I put the lineXBTUSD.run_forever()before app.run_server(debug=True) only one part of the code will be executed and my whole Dash app won't run until I stop the first part of the code. Same happens if I do the opposite.



    So the problem is XBTUSD.run_forever(), but I can't just remove that line because it won't run data.py. Is there a way to solve this?



    I am now thinking of running two separated scripts with one sending data to a DB and the other one should query the DB, retrieve the data and chart it, but I don't know if it's the best solution because a) I'll be handling a lot of data every minute b) I don't know if it'll work when deployed online (on heroku, for example)










    share|improve this question


























      up vote
      4
      down vote

      favorite









      up vote
      4
      down vote

      favorite











      I want to create a Python app where some data is retrieved and charted on a Dash app.



      This is the Dash part. This is where my whole data will be sent and shown on a webpage, since I'm starting now, this is just a basic example of a live chart.



      main.py



      import dash
      from dash.dependencies import Output, Event
      import dash_core_components as dcc
      import dash_html_components as html
      import plotly
      import random
      import plotly.graph_objs as go
      from collections import deque

      app = dash.Dash(__name__)
      app.layout = html.Div(
      [
      dcc.Graph(id='live-graph', animate=True),
      dcc.Interval(
      id='graph-update',
      interval=1*1000
      ),
      ]
      )

      @app.callback(Output('live-graph', 'figure'),
      events=[Event('graph-update', 'interval')])
      def update_graph_scatter():
      X.append(X[-1]+1)
      Y.append(Y[-1]+Y[-1]*random.uniform(-0.1,0.1))

      data = plotly.graph_objs.Scatter(
      x=list(X),
      y=list(Y),
      name='Scatter',
      mode= 'lines+markers'
      )

      return {'data': [data],'layout' : go.Layout(xaxis=dict(range=[min(X),max(X)]), yaxis=dict(range=[min(Y),max(Y)]),)}

      if __name__ == '__main__':
      app.run_server(debug=True)


      This is the Python part where the data is retrieved, connecting to a Websocket.
      data.py



      import websocket
      import json
      from bitmex_websocket import Instrument
      from bitmex_websocket.constants import InstrumentChannels
      from bitmex_websocket.constants import Channels

      websocket.enableTrace(True)

      channels = [
      InstrumentChannels.trade,
      ]

      XBTUSD = Instrument(symbol='XBTUSD',
      channels=channels)
      XBTUSD.on('action', lambda msg: test(msg))

      XBTUSD = Instrument(symbol='XBTUSD',
      channels=channels)

      XBTUSD.on('action', lambda msg: rekter(msg))

      def rekter(msg):

      if msg['table'] =='trade':
      Rate = msg['data'][0]['price']

      print(Rate)


      XBTUSD.run_forever()


      I tried to accomplish that by using imports, so I imported as a module my script, but that didn't work either:



      from trades import XBTUSD
      import dash
      from dash.dependencies import Output, Event
      import dash_core_components as dcc
      import dash_html_components as html
      import plotly
      import random
      import plotly.graph_objs as go
      from collections import deque


      X = deque(maxlen=2000)
      X.append(1)
      Y = deque(maxlen=2000)
      Y.append(1)


      app = dash.Dash(__name__)
      app.layout = html.Div(
      [
      dcc.Graph(id='live-graph', animate=True),
      dcc.Interval(
      id='graph-update',
      interval=1*1000
      ),
      ]
      )

      @app.callback(Output('live-graph', 'figure'),
      events=[Event('graph-update', 'interval')])
      def update_graph_scatter():
      X.append(X[-1]+1)
      Y.append(Y[-1]+Y[-1]*random.uniform(-0.1,0.1))

      data = plotly.graph_objs.Scatter(
      x=list(X),
      y=list(Y),
      name='Scatter',
      mode= 'lines+markers'
      )

      return {'data': [data],'layout' : go.Layout(xaxis=dict(range=[min(X),max(X)]),
      yaxis=dict(range=[min(Y),max(Y)]),)}



      if __name__ == '__main__':
      app.run_server(debug=True)

      XBTUSD.run_forever()


      Other than that, I tried turning it into modules, but it didn't work either.



      My problem is that I don't know how to "embed" my second part into the first part. I tried do that, but if I put the lineXBTUSD.run_forever()before app.run_server(debug=True) only one part of the code will be executed and my whole Dash app won't run until I stop the first part of the code. Same happens if I do the opposite.



      So the problem is XBTUSD.run_forever(), but I can't just remove that line because it won't run data.py. Is there a way to solve this?



      I am now thinking of running two separated scripts with one sending data to a DB and the other one should query the DB, retrieve the data and chart it, but I don't know if it's the best solution because a) I'll be handling a lot of data every minute b) I don't know if it'll work when deployed online (on heroku, for example)










      share|improve this question















      I want to create a Python app where some data is retrieved and charted on a Dash app.



      This is the Dash part. This is where my whole data will be sent and shown on a webpage, since I'm starting now, this is just a basic example of a live chart.



      main.py



      import dash
      from dash.dependencies import Output, Event
      import dash_core_components as dcc
      import dash_html_components as html
      import plotly
      import random
      import plotly.graph_objs as go
      from collections import deque

      app = dash.Dash(__name__)
      app.layout = html.Div(
      [
      dcc.Graph(id='live-graph', animate=True),
      dcc.Interval(
      id='graph-update',
      interval=1*1000
      ),
      ]
      )

      @app.callback(Output('live-graph', 'figure'),
      events=[Event('graph-update', 'interval')])
      def update_graph_scatter():
      X.append(X[-1]+1)
      Y.append(Y[-1]+Y[-1]*random.uniform(-0.1,0.1))

      data = plotly.graph_objs.Scatter(
      x=list(X),
      y=list(Y),
      name='Scatter',
      mode= 'lines+markers'
      )

      return {'data': [data],'layout' : go.Layout(xaxis=dict(range=[min(X),max(X)]), yaxis=dict(range=[min(Y),max(Y)]),)}

      if __name__ == '__main__':
      app.run_server(debug=True)


      This is the Python part where the data is retrieved, connecting to a Websocket.
      data.py



      import websocket
      import json
      from bitmex_websocket import Instrument
      from bitmex_websocket.constants import InstrumentChannels
      from bitmex_websocket.constants import Channels

      websocket.enableTrace(True)

      channels = [
      InstrumentChannels.trade,
      ]

      XBTUSD = Instrument(symbol='XBTUSD',
      channels=channels)
      XBTUSD.on('action', lambda msg: test(msg))

      XBTUSD = Instrument(symbol='XBTUSD',
      channels=channels)

      XBTUSD.on('action', lambda msg: rekter(msg))

      def rekter(msg):

      if msg['table'] =='trade':
      Rate = msg['data'][0]['price']

      print(Rate)


      XBTUSD.run_forever()


      I tried to accomplish that by using imports, so I imported as a module my script, but that didn't work either:



      from trades import XBTUSD
      import dash
      from dash.dependencies import Output, Event
      import dash_core_components as dcc
      import dash_html_components as html
      import plotly
      import random
      import plotly.graph_objs as go
      from collections import deque


      X = deque(maxlen=2000)
      X.append(1)
      Y = deque(maxlen=2000)
      Y.append(1)


      app = dash.Dash(__name__)
      app.layout = html.Div(
      [
      dcc.Graph(id='live-graph', animate=True),
      dcc.Interval(
      id='graph-update',
      interval=1*1000
      ),
      ]
      )

      @app.callback(Output('live-graph', 'figure'),
      events=[Event('graph-update', 'interval')])
      def update_graph_scatter():
      X.append(X[-1]+1)
      Y.append(Y[-1]+Y[-1]*random.uniform(-0.1,0.1))

      data = plotly.graph_objs.Scatter(
      x=list(X),
      y=list(Y),
      name='Scatter',
      mode= 'lines+markers'
      )

      return {'data': [data],'layout' : go.Layout(xaxis=dict(range=[min(X),max(X)]),
      yaxis=dict(range=[min(Y),max(Y)]),)}



      if __name__ == '__main__':
      app.run_server(debug=True)

      XBTUSD.run_forever()


      Other than that, I tried turning it into modules, but it didn't work either.



      My problem is that I don't know how to "embed" my second part into the first part. I tried do that, but if I put the lineXBTUSD.run_forever()before app.run_server(debug=True) only one part of the code will be executed and my whole Dash app won't run until I stop the first part of the code. Same happens if I do the opposite.



      So the problem is XBTUSD.run_forever(), but I can't just remove that line because it won't run data.py. Is there a way to solve this?



      I am now thinking of running two separated scripts with one sending data to a DB and the other one should query the DB, retrieve the data and chart it, but I don't know if it's the best solution because a) I'll be handling a lot of data every minute b) I don't know if it'll work when deployed online (on heroku, for example)







      python






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 8 at 15:21









      Ctrl S

      505323




      505323










      asked Nov 8 at 13:43









      Jack022

      4310




      4310
























          1 Answer
          1






          active

          oldest

          votes

















          up vote
          2
          down vote













          The answer is threading or multiprocessing, which will allow both methods to run at the same time. Changes to mutable objects take place in both threads/processes, so you would be able to communicate between your two functions as such. This post provides clarity on the issue.






          share|improve this answer

















          • 1




            Sounds like a valid solution, but would it allow me to "share" data/variable etc between the two scripts and would it work when deployed online, for example on Heroku?
            – Jack022
            Nov 8 at 20:54










          • As long as the data is mutable, i.e. not just a string or number, and as far as Heroku goes, a quick search looks like it's not impossible.
            – mhoffman2016
            Nov 9 at 2:17











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53208993%2fcant-run-my-python-script-with-two-functions-inside%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          2
          down vote













          The answer is threading or multiprocessing, which will allow both methods to run at the same time. Changes to mutable objects take place in both threads/processes, so you would be able to communicate between your two functions as such. This post provides clarity on the issue.






          share|improve this answer

















          • 1




            Sounds like a valid solution, but would it allow me to "share" data/variable etc between the two scripts and would it work when deployed online, for example on Heroku?
            – Jack022
            Nov 8 at 20:54










          • As long as the data is mutable, i.e. not just a string or number, and as far as Heroku goes, a quick search looks like it's not impossible.
            – mhoffman2016
            Nov 9 at 2:17















          up vote
          2
          down vote













          The answer is threading or multiprocessing, which will allow both methods to run at the same time. Changes to mutable objects take place in both threads/processes, so you would be able to communicate between your two functions as such. This post provides clarity on the issue.






          share|improve this answer

















          • 1




            Sounds like a valid solution, but would it allow me to "share" data/variable etc between the two scripts and would it work when deployed online, for example on Heroku?
            – Jack022
            Nov 8 at 20:54










          • As long as the data is mutable, i.e. not just a string or number, and as far as Heroku goes, a quick search looks like it's not impossible.
            – mhoffman2016
            Nov 9 at 2:17













          up vote
          2
          down vote










          up vote
          2
          down vote









          The answer is threading or multiprocessing, which will allow both methods to run at the same time. Changes to mutable objects take place in both threads/processes, so you would be able to communicate between your two functions as such. This post provides clarity on the issue.






          share|improve this answer












          The answer is threading or multiprocessing, which will allow both methods to run at the same time. Changes to mutable objects take place in both threads/processes, so you would be able to communicate between your two functions as such. This post provides clarity on the issue.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 8 at 14:09









          mhoffman2016

          706




          706








          • 1




            Sounds like a valid solution, but would it allow me to "share" data/variable etc between the two scripts and would it work when deployed online, for example on Heroku?
            – Jack022
            Nov 8 at 20:54










          • As long as the data is mutable, i.e. not just a string or number, and as far as Heroku goes, a quick search looks like it's not impossible.
            – mhoffman2016
            Nov 9 at 2:17














          • 1




            Sounds like a valid solution, but would it allow me to "share" data/variable etc between the two scripts and would it work when deployed online, for example on Heroku?
            – Jack022
            Nov 8 at 20:54










          • As long as the data is mutable, i.e. not just a string or number, and as far as Heroku goes, a quick search looks like it's not impossible.
            – mhoffman2016
            Nov 9 at 2:17








          1




          1




          Sounds like a valid solution, but would it allow me to "share" data/variable etc between the two scripts and would it work when deployed online, for example on Heroku?
          – Jack022
          Nov 8 at 20:54




          Sounds like a valid solution, but would it allow me to "share" data/variable etc between the two scripts and would it work when deployed online, for example on Heroku?
          – Jack022
          Nov 8 at 20:54












          As long as the data is mutable, i.e. not just a string or number, and as far as Heroku goes, a quick search looks like it's not impossible.
          – mhoffman2016
          Nov 9 at 2:17




          As long as the data is mutable, i.e. not just a string or number, and as far as Heroku goes, a quick search looks like it's not impossible.
          – mhoffman2016
          Nov 9 at 2:17


















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53208993%2fcant-run-my-python-script-with-two-functions-inside%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          這個網誌中的熱門文章

          Academy of Television Arts & Sciences

          L'Équipe

          1995 France bombings