0

I´m trying to get access to a variable from a python script to the command lines.

I run following command line with several args:

!python test.py --model I3D_resnet50 --dataset kinetics400

In this test.py there is variable Test1. If I use sys.exit(Test1) in test.py there will be just the value printed in the command line, but I need the value saved in a variable.

Is this possible?

3
  • 3
    It is easier to import that module (test) from your code and call the function that (hopefully) return that value instead of running it on the command line. It depends on how test.py is written. Commented Oct 1, 2020 at 23:29
  • Just write the value with print, rather than sys.exit (which will make your script appear to have failed). !python suggests you are running your command from a Jupyter notebook; I am not sure how to capture the output in that environment. (From the shell, you would write x=$(python test.py python test.py --model I3D_resnet50 --dataset kinetics400). Commented Oct 2, 2020 at 0:04
  • Thanks chepner, worked with this solution. x=!(python test.py --model I3D_resnet50 --dataset kinetics400) variable=x[-1] print(variable) Commented Oct 2, 2020 at 0:17

2 Answers 2

1

It depends on your shell. With *nix, you can do something like

test.py

var = 'Something'
print (var)

and then in the shell

x=$(python test.py)

x will be whatever went to stdout. In this case,

echo $x
Something

If your in Windows, you'll need something like this.

Sign up to request clarification or add additional context in comments.

2 Comments

!python ... suggests the OP is running their script from inside a Jupyter notebook, or at least some other non-shell environment.
yes running the script on Google Colab, but thanks Wyrmwood, your explanation helped me a lot.
0

There are some ways, but most will run a subshell, so you won't have access to the environment variables in the shell you're running the script from.

Did you just want to see what a variable is? In that case, you can use

import os
os.system('echo '+var_of_interest)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.