简体   繁体   中英

how to pass python script variables to a csh script?

I have a python script which asks user to selct one of many options, I would like to use the selected variable in a csh script to proceed further. I am getting undefined variable when I am trying to use the python variable from the shell script.

Here is some reference:

There is a python script choices.py whose output is something like this:

Select a Choice:
1) choice1
2) choice2
3) choice3
Choice: 1
Selected Choice: choice1

Then in my csh script I am envoking the python script and trying to use the choice variable for subsequent operations. Something like this:

python choices.py
echo "$choice"

Getting the error:

choice: Undefined variable.

Is there a way to make the python variable global so that it can be used in other places?

Expected:

choice1

Getting the error:

choice: Undefined variable.

Csh has no way to know what variables existed in a Python process which has now ceased to exist, just like you have no way to know what C variables exist internally in the C compiler.

A common arrangement is to have your script output a value on standard output, and have the shell capture that:

set choice=`python choices.py`
echo "$choice"

Of course, if your script already needs standard output for other things (like communicating with the user.) you need a slightly different approach, Perhaps it can write the value to a file? and have the caller read that file?

More tangentially, the C shell has basically been abandoned by all its sane users some 30+ years ago in favor of Bourne-compatible shells. You generally do not want to write scripts using csh syntax unless you are writing them strictly for your own private use and you have a very odd masochistic fetish. The standard reference for persuading people to switch is Csh considered harmful though some of the arguments in that are slightly dubious; the conclusion is still forcefully argued with sane arguments even after you ignore some of the spurious ones. Perhaps see also https://www.grymoire.com/Unix/CshTop10.txt

Here is the same construct in standard POSIX sh syntax:

#!/bin/sh
choice=$(python choices.py)
echo "$choice"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM